]> git.lyx.org Git - lyx.git/blob - src/insets/InsetTabular.cpp
More sensible longtable caption handling (needed for bug #7412)
[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(bool withcaptions) 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                     (withcaptions || !row_info[i].caption))
1916                         return true;
1917         return false;
1918 }
1919
1920
1921 bool Tabular::haveLTFirstHead(bool withcaptions) const
1922 {
1923         if (!is_long_tabular || endfirsthead.empty)
1924                 return false;
1925         for (row_type r = 0; r < nrows(); ++r)
1926                 if (row_info[r].endfirsthead &&
1927                     (withcaptions || !row_info[r].caption))
1928                         return true;
1929         return false;
1930 }
1931
1932
1933 bool Tabular::haveLTFoot(bool withcaptions) const
1934 {
1935         if (!is_long_tabular)
1936                 return false;
1937         for (row_type r = 0; r < nrows(); ++r)
1938                 if (row_info[r].endfoot &&
1939                     (withcaptions || !row_info[r].caption))
1940                         return true;
1941         return false;
1942 }
1943
1944
1945 bool Tabular::haveLTLastFoot(bool withcaptions) const
1946 {
1947         if (!is_long_tabular || endlastfoot.empty)
1948                 return false;
1949         for (row_type r = 0; r < nrows(); ++r)
1950                 if (row_info[r].endlastfoot &&
1951                     (withcaptions || !row_info[r].caption))
1952                         return true;
1953         return false;
1954 }
1955
1956
1957 Tabular::idx_type Tabular::setLTCaption(row_type row, bool what)
1958 {
1959         idx_type i = getFirstCellInRow(row);
1960         if (what) {
1961                 setMultiColumn(i, numberOfCellsInRow(row), false);
1962                 setTopLine(i, false);
1963                 setBottomLine(i, false);
1964                 setLeftLine(i, false);
1965                 setRightLine(i, false);
1966                 if (!row_info[row].endfirsthead && !row_info[row].endhead &&
1967                     !row_info[row].endfoot && !row_info[row].endlastfoot) {
1968                         setLTHead(row, true, endfirsthead, true);
1969                         row_info[row].endfirsthead = true;
1970                 }
1971         } else {
1972                 unsetMultiColumn(i);
1973                 // When unsetting a caption row, also all existing
1974                 // captions in this row must be dissolved.
1975         }
1976         row_info[row].caption = what;
1977         return i;
1978 }
1979
1980
1981 bool Tabular::ltCaption(row_type row) const
1982 {
1983         return row_info[row].caption;
1984 }
1985
1986
1987 bool Tabular::haveLTCaption(CaptionType captiontype) const
1988 {
1989         if (!is_long_tabular)
1990                 return false;
1991         for (row_type r = 0; r < nrows(); ++r) {
1992                 if (row_info[r].caption) {
1993                         switch (captiontype) {
1994                         case CAPTION_FIRSTHEAD:
1995                                 if (row_info[r].endfirsthead)
1996                                         return true;
1997                                 break;
1998                         case CAPTION_HEAD:
1999                                 if (row_info[r].endhead)
2000                                         return true;
2001                                 break;
2002                         case CAPTION_FOOT:
2003                                 if (row_info[r].endfoot)
2004                                         return true;
2005                                 break;
2006                         case CAPTION_LASTFOOT:
2007                                 if (row_info[r].endlastfoot)
2008                                         return true;
2009                                 break;
2010                         case CAPTION_ANY:
2011                                 return true;
2012                         }
2013                 }
2014         }
2015         return false;
2016 }
2017
2018
2019 // end longtable support functions
2020
2021 void Tabular::setRowAscent(row_type row, int height)
2022 {
2023         if (row >= nrows() || row_info[row].ascent == height)
2024                 return;
2025         row_info[row].ascent = height;
2026 }
2027
2028
2029 void Tabular::setRowDescent(row_type row, int height)
2030 {
2031         if (row >= nrows() || row_info[row].descent == height)
2032                 return;
2033         row_info[row].descent = height;
2034 }
2035
2036
2037 int Tabular::rowAscent(row_type row) const
2038 {
2039         LASSERT(row < nrows(), /**/);
2040         return row_info[row].ascent;
2041 }
2042
2043
2044 int Tabular::rowDescent(row_type row) const
2045 {
2046         LASSERT(row < nrows(), /**/);
2047         return row_info[row].descent;
2048 }
2049
2050
2051 int Tabular::height() const
2052 {
2053         int height = 0;
2054         for (row_type row = 0; row < nrows(); ++row)
2055                 height += rowAscent(row) + rowDescent(row) +
2056                         interRowSpace(row);
2057         return height;
2058 }
2059
2060
2061 bool Tabular::isPartOfMultiColumn(row_type row, col_type column) const
2062 {
2063         LASSERT(row < nrows(), /**/);
2064         LASSERT(column < ncols(), /**/);
2065         return cell_info[row][column].multicolumn == CELL_PART_OF_MULTICOLUMN;
2066 }
2067
2068
2069 bool Tabular::isPartOfMultiRow(row_type row, col_type column) const
2070 {
2071         LASSERT(row < nrows(), /**/);
2072         LASSERT(column < ncols(), /**/);
2073         return cell_info[row][column].multirow == CELL_PART_OF_MULTIROW;
2074 }
2075
2076
2077 void Tabular::TeXTopHLine(otexstream & os, row_type row, string const lang) const
2078 {
2079         // we only output complete row lines and the 1st row here, the rest
2080         // is done in Tabular::TeXBottomHLine(...)
2081
2082         // get for each column the topline (if any)
2083         vector<bool> topline;
2084         col_type nset = 0;
2085         for (col_type c = 0; c < ncols(); ++c) {
2086                 topline.push_back(topLine(cellIndex(row, c)));
2087                 // If cell is part of a multirow and not the first cell of the
2088                 // multirow, no line must be drawn.
2089                 if (row != 0)
2090                         if (isMultiRow(cellIndex(row, c))
2091                             && cell_info[row][c].multirow != CELL_BEGIN_OF_MULTIROW)
2092                                 topline[c] = false;
2093                 if (topline[c])
2094                         ++nset;
2095         }
2096
2097         // do nothing if empty first row, or incomplete row line after
2098         if ((row == 0 && nset == 0) || (row > 0 && nset != ncols()))
2099                 return;
2100
2101         // only output complete row lines and the 1st row's clines
2102         if (nset == ncols()) {
2103                 if (use_booktabs) {
2104                         os << (row == 0 ? "\\toprule " : "\\midrule ");
2105                 } else {
2106                         os << "\\hline ";
2107                 }
2108         } else if (row == 0) {
2109                 for (col_type c = 0; c < ncols(); ++c) {
2110                         if (topline[c]) {
2111                                 col_type offset = 0;
2112                                 for (col_type j = 0 ; j < c; ++j)
2113                                         if (column_info[j].alignment == LYX_ALIGN_DECIMAL)
2114                                                 ++offset;
2115                                 
2116                                 //babel makes the "-" character an active one, so we have to suppress this here
2117                                 //see http://groups.google.com/group/comp.text.tex/browse_thread/thread/af769424a4a0f289#
2118                                 if (lang == "slovak" || lang == "czech")
2119                                         os << "\\expandafter" << (use_booktabs ? "\\cmidrule" : "\\cline") 
2120                                         << "\\expandafter{\\expandafter" << c + 1 + offset << "\\string-";
2121                                 else
2122                                         os << (use_booktabs ? "\\cmidrule{" : "\\cline{") << c + 1 + offset << '-';
2123                                 
2124                                 col_type cstart = c;
2125                                 for ( ; c < ncols() && topline[c]; ++c) {}
2126                                 
2127                                 for (col_type j = cstart ; j < c ; ++j)
2128                                         if (column_info[j].alignment == LYX_ALIGN_DECIMAL)
2129                                                 ++offset;
2130                                 
2131                                 os << c + offset << "} ";
2132                         }
2133                 }
2134         }
2135         os << "\n";
2136 }
2137
2138
2139 void Tabular::TeXBottomHLine(otexstream & os, row_type row, string const lang) const
2140 {
2141         // we output bottomlines of row r and the toplines of row r+1
2142         // if the latter do not span the whole tabular
2143
2144         // get the bottomlines of row r, and toplines in next row
2145         bool lastrow = row == nrows() - 1;
2146         vector<bool> bottomline, topline;
2147         bool nextrowset = true;
2148         for (col_type c = 0; c < ncols(); ++c) {
2149                 bottomline.push_back(bottomLine(cellIndex(row, c)));
2150                 topline.push_back(!lastrow && topLine(cellIndex(row + 1, c)));
2151                 // If cell is part of a multirow and not the last cell of the
2152                 // multirow, no line must be drawn.
2153                 if (!lastrow)
2154                         if (isMultiRow(cellIndex(row, c))
2155                             && isMultiRow(cellIndex(row + 1, c))
2156                             && cell_info[row + 1][c].multirow != CELL_BEGIN_OF_MULTIROW) {
2157                                 bottomline[c] = false;
2158                                 topline[c] = false;
2159                                 }
2160                 nextrowset &= topline[c];
2161         }
2162
2163         // combine this row's bottom lines and next row's toplines if necessary
2164         col_type nset = 0;
2165         for (col_type c = 0; c < ncols(); ++c) {
2166                 if (!nextrowset)
2167                         bottomline[c] = bottomline[c] || topline[c];
2168                 if (bottomline[c])
2169                         ++nset;
2170         }
2171
2172         // do nothing if empty, OR incomplete row line with a topline in next row
2173         if (nset == 0 || (nextrowset && nset != ncols()))
2174                 return;
2175
2176         if (nset == ncols()) {
2177                 if (use_booktabs)
2178                         os << (lastrow ? "\\bottomrule" : "\\midrule");
2179                 else
2180                         os << "\\hline ";
2181         } else {
2182                 for (col_type c = 0; c < ncols(); ++c) {
2183                         if (bottomline[c]) {
2184                                 col_type offset = 0;
2185                                 for (col_type j = 0 ; j < c; ++j)
2186                                         if (column_info[j].alignment == LYX_ALIGN_DECIMAL)
2187                                                 ++offset;
2188                                 
2189                                 //babel makes the "-" character an active one, so we have to suppress this here
2190                                 //see http://groups.google.com/group/comp.text.tex/browse_thread/thread/af769424a4a0f289#
2191                                 if (lang == "slovak" || lang == "czech")
2192                                         os << "\\expandafter" << (use_booktabs ? "\\cmidrule" : "\\cline")
2193                                         << "\\expandafter{\\expandafter" << c + 1 + offset << "\\string-";
2194                                 else
2195                                         os << (use_booktabs ? "\\cmidrule{" : "\\cline{") << c + 1 + offset << '-';
2196                                 
2197                                 col_type cstart = c;
2198                                 for ( ; c < ncols() && bottomline[c]; ++c) {}
2199                                 
2200                                 for (col_type j = cstart ; j < c ; ++j)
2201                                         if (column_info[j].alignment == LYX_ALIGN_DECIMAL)
2202                                                 ++offset;
2203                                 
2204                                 os << c + offset << "} ";
2205                         }
2206                 }
2207         }
2208         os << "\n";
2209 }
2210
2211
2212 void Tabular::TeXCellPreamble(otexstream & os, idx_type cell,
2213                               bool & ismulticol, bool & ismultirow) const
2214 {
2215         row_type const r = cellRow(cell);
2216         if (is_long_tabular && row_info[r].caption)
2217                 return;
2218
2219         Tabular::VAlignment valign =  getVAlignment(cell, !isMultiColumn(cell));
2220         LyXAlignment align = getAlignment(cell, !isMultiColumn(cell));
2221         // figure out how to set the lines
2222         // we always set double lines to the right of the cell
2223         col_type const c = cellColumn(cell);
2224         col_type const nextcol = c + columnSpan(cell);
2225         bool colright = columnRightLine(c);
2226         bool colleft = columnLeftLine(c);
2227         bool nextcolleft = nextcol < ncols() && columnLeftLine(nextcol);
2228         bool nextcellleft = nextcol < ncols() 
2229                 && leftLine(cellIndex(r, nextcol));
2230         bool coldouble = colright && nextcolleft;
2231         bool celldouble = rightLine(cell) && nextcellleft;
2232
2233         ismulticol = isMultiColumn(cell)
2234                 || (c == 0 && colleft != leftLine(cell))
2235                 || ((colright || nextcolleft) && !rightLine(cell) && !nextcellleft)
2236                 || (!colright && !nextcolleft && (rightLine(cell) || nextcellleft))
2237                 || (coldouble != celldouble);
2238
2239         // we center in multicol when no decimal point
2240         if (column_info[c].alignment == LYX_ALIGN_DECIMAL) {
2241                 docstring const align_d = column_info[c].decimal_point;
2242                 DocIterator const dit = separatorPos(cellInset(cell).get(), align_d);
2243                 ismulticol |= !dit;
2244         }
2245
2246         // up counter by 1 for each decimally aligned col since they use 2 latex cols
2247         int latexcolspan = columnSpan(cell);
2248         for(col_type col = c; col < c + columnSpan(cell); ++col)
2249                 if (column_info[col].alignment == LYX_ALIGN_DECIMAL)
2250                         ++latexcolspan;
2251
2252         if (ismulticol) {
2253                 os << "\\multicolumn{" << latexcolspan << "}{";
2254                 if (c ==0 && leftLine(cell))
2255                         os << '|';
2256                 if (!cellInfo(cell).align_special.empty()) {
2257                         os << cellInfo(cell).align_special;
2258                 } else {
2259                         if (!getPWidth(cell).zero()) {
2260                                 switch (align) {
2261                                 case LYX_ALIGN_LEFT:
2262                                         os << ">{\\raggedright}";
2263                                         break;
2264                                 case LYX_ALIGN_RIGHT:
2265                                         os << ">{\\raggedleft}";
2266                                         break;
2267                                 case LYX_ALIGN_CENTER:
2268                                         os << ">{\\centering}";
2269                                         break;
2270                                 default:
2271                                         break;
2272                                 }
2273                                 switch (valign) {
2274                                 case LYX_VALIGN_TOP:
2275                                         os << 'p';
2276                                         break;
2277                                 case LYX_VALIGN_MIDDLE:
2278                                         os << 'm';
2279                                         break;
2280                                 case LYX_VALIGN_BOTTOM:
2281                                         os << 'b';
2282                                         break;
2283                                 }
2284                                 os << '{'
2285                                    << from_ascii(getPWidth(cell).asLatexString())
2286                                    << '}';
2287                         } else {
2288                                 switch (align) {
2289                                 case LYX_ALIGN_LEFT:
2290                                         os << 'l';
2291                                         break;
2292                                 case LYX_ALIGN_RIGHT:
2293                                         os << 'r';
2294                                         break;
2295                                 default:
2296                                         os << 'c';
2297                                         break;
2298                                 }
2299                         } // end if else !getPWidth
2300                 } // end if else !cellinfo_of_cell
2301                 if (rightLine(cell) || nextcellleft)
2302                         os << '|';
2303                 if (celldouble)
2304                         // add extra vertical line if we want a double one
2305                         os << '|';
2306                 os << "}{";
2307         } // end if ismulticol
2308
2309         // we only need code for the first multirow cell
2310         ismultirow = isMultiRow(cell);
2311         if (ismultirow) {
2312                 os << "\\multirow{" << rowSpan(cell) << "}{";
2313                 if (!getPWidth(cell).zero())
2314                         os << from_ascii(getPWidth(cell).asLatexString());
2315                 else
2316                         // we need to set a default value
2317                         os << "*";
2318                 os << "}";
2319                 if (!getMROffset(cell).zero())
2320                         os << "[" << from_ascii(getMROffset(cell).asLatexString()) << "]";
2321                 os << "{";
2322         } // end if ismultirow
2323
2324         if (getRotateCell(cell)) {
2325                 os << "\\begin{sideways}\n";
2326         }
2327         if (getUsebox(cell) == BOX_PARBOX) {
2328                 os << "\\parbox[";
2329                 switch (valign) {
2330                 case LYX_VALIGN_TOP:
2331                         os << 't';
2332                         break;
2333                 case LYX_VALIGN_MIDDLE:
2334                         os << 'c';
2335                         break;
2336                 case LYX_VALIGN_BOTTOM:
2337                         os << 'b';
2338                         break;
2339                 }
2340                 os << "]{" << from_ascii(getPWidth(cell).asLatexString())
2341                    << "}{";
2342         } else if (getUsebox(cell) == BOX_MINIPAGE) {
2343                 os << "\\begin{minipage}[";
2344                 switch (valign) {
2345                 case LYX_VALIGN_TOP:
2346                         os << 't';
2347                         break;
2348                 case LYX_VALIGN_MIDDLE:
2349                         os << 'm';
2350                         break;
2351                 case LYX_VALIGN_BOTTOM:
2352                         os << 'b';
2353                         break;
2354                 }
2355                 os << "]{" << from_ascii(getPWidth(cell).asLatexString())
2356                    << "}\n";
2357         }
2358 }
2359
2360
2361 void Tabular::TeXCellPostamble(otexstream & os, idx_type cell,
2362                                bool ismulticol, bool ismultirow) const
2363 {
2364         row_type const r = cellRow(cell);
2365         if (is_long_tabular && row_info[r].caption)
2366                 return;
2367
2368         // usual cells
2369         if (getUsebox(cell) == BOX_PARBOX)
2370                 os << '}';
2371         else if (getUsebox(cell) == BOX_MINIPAGE)
2372                 os << breakln << "\\end{minipage}";
2373         if (getRotateCell(cell))
2374                 os << breakln << "\\end{sideways}";
2375         if (ismultirow)
2376                 os << '}';
2377         if (ismulticol)
2378                 os << '}';
2379 }
2380
2381
2382 void Tabular::TeXLongtableHeaderFooter(otexstream & os,
2383                                         OutputParams const & runparams) const
2384 {
2385         if (!is_long_tabular)
2386                 return;
2387
2388         // output first header info
2389         if (haveLTFirstHead()) {
2390                 if (endfirsthead.topDL)
2391                         os << "\\hline\n";
2392                 for (row_type r = 0; r < nrows(); ++r) {
2393                         if (row_info[r].endfirsthead)
2394                                 TeXRow(os, r, runparams);
2395                 }
2396                 if (endfirsthead.bottomDL)
2397                         os << "\\hline\n";
2398                 os << "\\endfirsthead\n";
2399         }
2400         // output header info
2401         if (haveLTHead()) {
2402                 if (endfirsthead.empty && !haveLTFirstHead())
2403                         os << "\\endfirsthead\n";
2404                 if (endhead.topDL)
2405                         os << "\\hline\n";
2406                 for (row_type r = 0; r < nrows(); ++r) {
2407                         if (row_info[r].endhead)
2408                                 TeXRow(os, r, runparams);
2409                 }
2410                 if (endhead.bottomDL)
2411                         os << "\\hline\n";
2412                 os << "\\endhead\n";
2413         }
2414         // output footer info
2415         if (haveLTFoot()) {
2416                 if (endfoot.topDL)
2417                         os << "\\hline\n";
2418                 for (row_type r = 0; r < nrows(); ++r) {
2419                         if (row_info[r].endfoot)
2420                                 TeXRow(os, r, runparams);
2421                 }
2422                 if (endfoot.bottomDL)
2423                         os << "\\hline\n";
2424                 os << "\\endfoot\n";
2425                 if (endlastfoot.empty && !haveLTLastFoot())
2426                         os << "\\endlastfoot\n";
2427         }
2428         // output lastfooter info
2429         if (haveLTLastFoot()) {
2430                 if (endlastfoot.topDL)
2431                         os << "\\hline\n";
2432                 for (row_type r = 0; r < nrows(); ++r) {
2433                         if (row_info[r].endlastfoot)
2434                                 TeXRow(os, r, runparams);
2435                 }
2436                 if (endlastfoot.bottomDL)
2437                         os << "\\hline\n";
2438                 os << "\\endlastfoot\n";
2439         }
2440 }
2441
2442
2443 bool Tabular::isValidRow(row_type row) const
2444 {
2445         if (!is_long_tabular)
2446                 return true;
2447         return !row_info[row].endhead && !row_info[row].endfirsthead
2448                 && !row_info[row].endfoot && !row_info[row].endlastfoot
2449                 && !row_info[row].caption;
2450 }
2451
2452
2453 void Tabular::TeXRow(otexstream & os, row_type row,
2454                      OutputParams const & runparams) const
2455 {
2456         idx_type cell = cellIndex(row, 0);
2457         shared_ptr<InsetTableCell> inset = cellInset(cell);
2458         Paragraph const & par = inset->paragraphs().front();
2459         string const lang = par.getParLanguage(buffer().params())->lang();
2460
2461         //output the top line
2462         TeXTopHLine(os, row, lang);
2463
2464         if (row_info[row].top_space_default) {
2465                 if (use_booktabs)
2466                         os << "\\addlinespace\n";
2467                 else
2468                         os << "\\noalign{\\vskip\\doublerulesep}\n";
2469         } else if(!row_info[row].top_space.zero()) {
2470                 if (use_booktabs)
2471                         os << "\\addlinespace["
2472                            << from_ascii(row_info[row].top_space.asLatexString())
2473                            << "]\n";
2474                 else {
2475                         os << "\\noalign{\\vskip"
2476                            << from_ascii(row_info[row].top_space.asLatexString())
2477                            << "}\n";
2478                 }
2479         }
2480         bool ismulticol = false;
2481         bool ismultirow = false;
2482         for (col_type c = 0; c < ncols(); ++c) {
2483                 if (isPartOfMultiColumn(row, c))
2484                         continue;
2485
2486                 cell = cellIndex(row, c);
2487
2488                 if (isPartOfMultiRow(row, c)
2489                     && column_info[c].alignment != LYX_ALIGN_DECIMAL) {
2490                         if (cell != getLastCellInRow(row))
2491                                 os << " & "; 
2492                         continue;
2493                 }
2494
2495                 TeXCellPreamble(os, cell, ismulticol, ismultirow);
2496                 shared_ptr<InsetTableCell> inset = cellInset(cell);
2497
2498                 Paragraph const & par = inset->paragraphs().front();
2499                 bool rtl = par.isRTL(buffer().params())
2500                         && !par.empty()
2501                         && getPWidth(cell).zero();
2502
2503                 if (rtl) {
2504                         string const lang =
2505                                 par.getParLanguage(buffer().params())->lang();
2506                         if (lang == "farsi")
2507                                 os << "\\textFR{";
2508                         else if (lang == "arabic_arabi")
2509                                 os << "\\textAR{";
2510                         // currently, remaining RTL languages are
2511                         // arabic_arabtex and hebrew
2512                         else
2513                                 os << "\\R{";
2514                 }
2515                 // pass to the OutputParams that we are in a cell and
2516                 // which alignment we have set.
2517                 // InsetNewline needs this context information.
2518                 OutputParams newrp(runparams);
2519                 newrp.inTableCell = (getAlignment(cell) == LYX_ALIGN_BLOCK)
2520                                     ? OutputParams::PLAIN
2521                                     : OutputParams::ALIGNED;
2522
2523                 if (getAlignment(cell) == LYX_ALIGN_DECIMAL) {
2524                         // copy cell and split in 2
2525                         InsetTableCell head = InsetTableCell(*cellInset(cell).get());
2526                         head.setBuffer(buffer());
2527                         DocIterator dit = cellInset(cell)->getText(0)->macrocontextPosition();
2528                         dit.pop_back();
2529                         dit.push_back(CursorSlice(head));
2530                         head.setMacrocontextPositionRecursive(dit);
2531                         bool hassep = false;
2532                         InsetTableCell tail = splitCell(head, column_info[c].decimal_point, hassep);
2533                         head.latex(os, newrp);
2534                         if (hassep) {
2535                                 os << '&';
2536                                 tail.setBuffer(head.buffer());
2537                                 dit.pop_back();
2538                                 dit.push_back(CursorSlice(tail));
2539                                 tail.setMacrocontextPositionRecursive(dit);
2540                                 tail.latex(os, newrp);
2541                         }
2542                 } else if (!isPartOfMultiRow(row, c)) {
2543                         if (!runparams.nice)
2544                                 os.texrow().start(par.id(), 0);
2545                         inset->latex(os, newrp);
2546                 }
2547
2548                 runparams.encoding = newrp.encoding;
2549                 if (rtl)
2550                         os << '}';
2551
2552                 TeXCellPostamble(os, cell, ismulticol, ismultirow);
2553                 if (cell != getLastCellInRow(row)) { // not last cell in row
2554                         if (runparams.nice)
2555                                 os << " & ";
2556                         else
2557                                 os << " &\n";
2558                 }
2559         }
2560         os << "\\tabularnewline";
2561         if (row_info[row].bottom_space_default) {
2562                 if (use_booktabs)
2563                         os << "\\addlinespace";
2564                 else
2565                         os << "[\\doublerulesep]";
2566         } else if (!row_info[row].bottom_space.zero()) {
2567                 if (use_booktabs)
2568                         os << "\\addlinespace";
2569                 os << '['
2570                    << from_ascii(row_info[row].bottom_space.asLatexString())
2571                    << ']';
2572         }
2573         os << '\n';
2574
2575         //output the bottom line
2576         TeXBottomHLine(os, row, lang);
2577
2578         if (row_info[row].interline_space_default) {
2579                 if (use_booktabs)
2580                         os << "\\addlinespace\n";
2581                 else
2582                         os << "\\noalign{\\vskip\\doublerulesep}\n";
2583         } else if (!row_info[row].interline_space.zero()) {
2584                 if (use_booktabs)
2585                         os << "\\addlinespace["
2586                            << from_ascii(row_info[row].interline_space.asLatexString())
2587                            << "]\n";
2588                 else
2589                         os << "\\noalign{\\vskip"
2590                            << from_ascii(row_info[row].interline_space.asLatexString())
2591                            << "}\n";
2592         }
2593 }
2594
2595
2596 void Tabular::latex(otexstream & os, OutputParams const & runparams) const
2597 {
2598         bool const is_tabular_star = !tabular_width.zero();
2599
2600         //+---------------------------------------------------------------------
2601         //+                      first the opening preamble                    +
2602         //+---------------------------------------------------------------------
2603
2604         os << safebreakln;
2605         if (runparams.lastid != -1)
2606                 os.texrow().start(runparams.lastid, runparams.lastpos);
2607
2608         if (rotate)
2609                 os << "\\begin{sideways}\n";
2610
2611         if (is_long_tabular) {
2612                 os << "\\begin{longtable}";
2613                 switch (longtabular_alignment) {
2614                 case LYX_LONGTABULAR_ALIGN_LEFT:
2615                         os << "[l]";
2616                         break;
2617                 case LYX_LONGTABULAR_ALIGN_CENTER:
2618                         break;
2619                 case LYX_LONGTABULAR_ALIGN_RIGHT:
2620                         os << "[r]";
2621                         break;
2622                 }
2623         } else {
2624                 if (is_tabular_star)
2625                         os << "\\begin{tabular*}{" << from_ascii(tabular_width.asLatexString()) << "}";
2626                 else
2627                         os << "\\begin{tabular}";
2628                 switch (tabular_valignment) {
2629                 case LYX_VALIGN_TOP:
2630                         os << "[t]";
2631                         break;
2632                 case LYX_VALIGN_MIDDLE:
2633                         break;
2634                 case LYX_VALIGN_BOTTOM:
2635                         os << "[b]";
2636                         break;
2637                 }
2638         }
2639         
2640         os << "{";
2641
2642         if (is_tabular_star)
2643                 os << "@{\\extracolsep{\\fill}}";
2644
2645         for (col_type c = 0; c < ncols(); ++c) {
2646                 if (columnLeftLine(c))
2647                         os << '|';
2648                 if (!column_info[c].align_special.empty()) {
2649                         os << column_info[c].align_special;
2650                 } else {
2651                         if (!column_info[c].p_width.zero()) {
2652                                 switch (column_info[c].alignment) {
2653                                 case LYX_ALIGN_LEFT:
2654                                         os << ">{\\raggedright}";
2655                                         break;
2656                                 case LYX_ALIGN_RIGHT:
2657                                         os << ">{\\raggedleft}";
2658                                         break;
2659                                 case LYX_ALIGN_CENTER:
2660                                         os << ">{\\centering}";
2661                                         break;
2662                                 case LYX_ALIGN_NONE:
2663                                 case LYX_ALIGN_BLOCK:
2664                                 case LYX_ALIGN_LAYOUT:
2665                                 case LYX_ALIGN_SPECIAL:
2666                                 case LYX_ALIGN_DECIMAL:
2667                                         break;
2668                                 }
2669
2670                                 switch (column_info[c].valignment) {
2671                                 case LYX_VALIGN_TOP:
2672                                         os << 'p';
2673                                         break;
2674                                 case LYX_VALIGN_MIDDLE:
2675                                         os << 'm';
2676                                         break;
2677                                 case LYX_VALIGN_BOTTOM:
2678                                         os << 'b';
2679                                         break;
2680                         }
2681                                 os << '{'
2682                                    << from_ascii(column_info[c].p_width.asLatexString())
2683                                    << '}';
2684                         } else {
2685                                 switch (column_info[c].alignment) {
2686                                 case LYX_ALIGN_LEFT:
2687                                         os << 'l';
2688                                         break;
2689                                 case LYX_ALIGN_RIGHT:
2690                                         os << 'r';
2691                                         break;
2692                                 case LYX_ALIGN_DECIMAL:
2693                                         os << "r@{\\extracolsep{0pt}" << column_info[c].decimal_point << "}l";
2694                                         break;
2695                                 default:
2696                                         os << 'c';
2697                                         break;
2698                                 }
2699                         } // end if else !column_info[i].p_width
2700                 } // end if else !column_info[i].align_special
2701                 if (columnRightLine(c))
2702                         os << '|';
2703         }
2704         os << "}\n";
2705
2706         TeXLongtableHeaderFooter(os, runparams);
2707
2708         //+---------------------------------------------------------------------
2709         //+                      the single row and columns (cells)            +
2710         //+---------------------------------------------------------------------
2711
2712         for (row_type r = 0; r < nrows(); ++r) {
2713                 if (isValidRow(r)) {
2714                         TeXRow(os, r, runparams);
2715                         if (is_long_tabular && row_info[r].newpage)
2716                                 os << "\\newpage\n";
2717                 }
2718         }
2719
2720         //+---------------------------------------------------------------------
2721         //+                      the closing of the tabular                    +
2722         //+---------------------------------------------------------------------
2723
2724         if (is_long_tabular)
2725                 os << "\\end{longtable}";
2726         else {
2727                 if (is_tabular_star)
2728                         os << "\\end{tabular*}";
2729                 else
2730                         os << "\\end{tabular}";
2731         }
2732
2733         if (rotate)
2734                 os << breakln << "\\end{sideways}";
2735 }
2736
2737
2738 int Tabular::docbookRow(odocstream & os, row_type row,
2739                            OutputParams const & runparams) const
2740 {
2741         int ret = 0;
2742         idx_type cell = getFirstCellInRow(row);
2743
2744         os << "<row>\n";
2745         for (col_type c = 0; c < ncols(); ++c) {
2746                 if (isPartOfMultiColumn(row, c))
2747                         continue;
2748
2749                 os << "<entry align=\"";
2750                 switch (getAlignment(cell)) {
2751                 case LYX_ALIGN_LEFT:
2752                         os << "left";
2753                         break;
2754                 case LYX_ALIGN_RIGHT:
2755                         os << "right";
2756                         break;
2757                 default:
2758                         os << "center";
2759                         break;
2760                 }
2761
2762                 os << "\" valign=\"";
2763                 switch (getVAlignment(cell)) {
2764                 case LYX_VALIGN_TOP:
2765                         os << "top";
2766                         break;
2767                 case LYX_VALIGN_BOTTOM:
2768                         os << "bottom";
2769                         break;
2770                 case LYX_VALIGN_MIDDLE:
2771                         os << "middle";
2772                 }
2773                 os << '"';
2774
2775                 if (isMultiColumn(cell)) {
2776                         os << " namest=\"col" << c << "\" ";
2777                         os << "nameend=\"col" << c + columnSpan(cell) - 1 << '"';
2778                 }
2779
2780                 os << '>';
2781                 ret += cellInset(cell)->docbook(os, runparams);
2782                 os << "</entry>\n";
2783                 ++cell;
2784         }
2785         os << "</row>\n";
2786         return ret;
2787 }
2788
2789
2790 int Tabular::docbook(odocstream & os, OutputParams const & runparams) const
2791 {
2792         int ret = 0;
2793
2794         //+---------------------------------------------------------------------
2795         //+                      first the opening preamble                    +
2796         //+---------------------------------------------------------------------
2797
2798         os << "<tgroup cols=\"" << ncols()
2799            << "\" colsep=\"1\" rowsep=\"1\">\n";
2800
2801         for (col_type c = 0; c < ncols(); ++c) {
2802                 os << "<colspec colname=\"col" << c << "\" align=\"";
2803                 switch (column_info[c].alignment) {
2804                 case LYX_ALIGN_LEFT:
2805                         os << "left";
2806                         break;
2807                 case LYX_ALIGN_RIGHT:
2808                         os << "right";
2809                         break;
2810                 default:
2811                         os << "center";
2812                         break;
2813                 }
2814                 os << '"';
2815                 if (runparams.flavor == OutputParams::XML)
2816                         os << '/';
2817                 os << ">\n";
2818                 ++ret;
2819         }
2820
2821         //+---------------------------------------------------------------------
2822         //+                      Long Tabular case                             +
2823         //+---------------------------------------------------------------------
2824
2825         // output caption info
2826         // The caption flag wins over head/foot
2827         if (haveLTCaption()) {
2828                 os << "<caption>\n";
2829                 ++ret;
2830                 for (row_type r = 0; r < nrows(); ++r) {
2831                         if (row_info[r].caption) {
2832                                 ret += docbookRow(os, r, runparams);
2833                         }
2834                 }
2835                 os << "</caption>\n";
2836                 ++ret;
2837         }
2838         // output header info
2839         if (haveLTHead(false) || haveLTFirstHead(false)) {
2840                 os << "<thead>\n";
2841                 ++ret;
2842                 for (row_type r = 0; r < nrows(); ++r) {
2843                         if ((row_info[r].endhead || row_info[r].endfirsthead) &&
2844                             !row_info[r].caption) {
2845                                 ret += docbookRow(os, r, runparams);
2846                         }
2847                 }
2848                 os << "</thead>\n";
2849                 ++ret;
2850         }
2851         // output footer info
2852         if (haveLTFoot(false) || haveLTLastFoot(false)) {
2853                 os << "<tfoot>\n";
2854                 ++ret;
2855                 for (row_type r = 0; r < nrows(); ++r) {
2856                         if ((row_info[r].endfoot || row_info[r].endlastfoot) &&
2857                             !row_info[r].caption) {
2858                                 ret += docbookRow(os, r, runparams);
2859                         }
2860                 }
2861                 os << "</tfoot>\n";
2862                 ++ret;
2863         }
2864
2865         //+---------------------------------------------------------------------
2866         //+                      the single row and columns (cells)            +
2867         //+---------------------------------------------------------------------
2868
2869         os << "<tbody>\n";
2870         ++ret;
2871         for (row_type r = 0; r < nrows(); ++r) {
2872                 if (isValidRow(r)) {
2873                         ret += docbookRow(os, r, runparams);
2874                 }
2875         }
2876         os << "</tbody>\n";
2877         ++ret;
2878         //+---------------------------------------------------------------------
2879         //+                      the closing of the tabular                    +
2880         //+---------------------------------------------------------------------
2881
2882         os << "</tgroup>";
2883         ++ret;
2884
2885         return ret;
2886 }
2887
2888
2889 docstring Tabular::xhtmlRow(XHTMLStream & xs, row_type row,
2890                            OutputParams const & runparams, bool header) const
2891 {
2892         docstring ret;
2893         string const celltag = header ? "th" : "td";
2894         idx_type cell = getFirstCellInRow(row);
2895
2896         xs << html::StartTag("tr");
2897         for (col_type c = 0; c < ncols(); ++c) {
2898                 if (isPartOfMultiColumn(row, c) || isPartOfMultiRow(row, c))
2899                         continue;
2900
2901                 stringstream attr;
2902                 attr << "align='";
2903                 switch (getAlignment(cell)) {
2904                 case LYX_ALIGN_LEFT:
2905                         attr << "left";
2906                         break;
2907                 case LYX_ALIGN_RIGHT:
2908                         attr << "right";
2909                         break;
2910                 default:
2911                         attr << "center";
2912                         break;
2913                 }
2914                 attr << "'";
2915                 attr << " valign='";
2916                 switch (getVAlignment(cell)) {
2917                 case LYX_VALIGN_TOP:
2918                         attr << "top";
2919                         break;
2920                 case LYX_VALIGN_BOTTOM:
2921                         attr << "bottom";
2922                         break;
2923                 case LYX_VALIGN_MIDDLE:
2924                         attr << "middle";
2925                 }
2926                 attr << "'";
2927
2928                 if (isMultiColumn(cell))
2929                         attr << " colspan='" << columnSpan(cell) << "'";
2930                 else if (isMultiRow(cell))
2931                         attr << " rowspan='" << rowSpan(cell) << "'";
2932
2933                 xs << html::StartTag(celltag, attr.str()) << html::CR();
2934                 ret += cellInset(cell)->xhtml(xs, runparams);
2935                 xs << html::EndTag(celltag) << html::CR();
2936                 ++cell;
2937         }
2938         xs << html::EndTag("tr");
2939         return ret;
2940 }
2941
2942
2943 docstring Tabular::xhtml(XHTMLStream & xs, OutputParams const & runparams) const
2944 {
2945         docstring ret;
2946
2947         if (is_long_tabular) {
2948                 // we'll wrap it in a div, so as to deal with alignment
2949                 string align;
2950                 switch (longtabular_alignment) {
2951                 case LYX_LONGTABULAR_ALIGN_LEFT:
2952                         align = "left";
2953                         break;
2954                 case LYX_LONGTABULAR_ALIGN_CENTER:
2955                         align = "center";
2956                         break;
2957                 case LYX_LONGTABULAR_ALIGN_RIGHT:
2958                         align = "right";
2959                         break;
2960                 }
2961                 xs << html::StartTag("div", "class='longtable' style='text-align: " + align + ";'")
2962                    << html::CR();
2963                 // The caption flag wins over head/foot
2964                 if (haveLTCaption()) {
2965                         xs << html::StartTag("div", "class='longtable-caption' style='text-align: " + align + ";'")
2966                            << html::CR();
2967                         for (row_type r = 0; r < nrows(); ++r)
2968                                 if (row_info[r].caption)
2969                                         ret += xhtmlRow(xs, r, runparams);
2970                         xs << html::EndTag("div") << html::CR();
2971                 }
2972         }
2973
2974         xs << html::StartTag("table") << html::CR();
2975
2976         // output header info
2977         bool const havefirsthead = haveLTFirstHead(false);
2978         // if we have a first head, then we are going to ignore the
2979         // headers for the additional pages, since there aren't any
2980         // in XHTML. this test accomplishes that.
2981         bool const havehead = !havefirsthead && haveLTHead(false);
2982         if (havehead || havefirsthead) {
2983                 xs << html::StartTag("thead") << html::CR();
2984                 for (row_type r = 0; r < nrows(); ++r) {
2985                         if (((havefirsthead && row_info[r].endfirsthead) ||
2986                              (havehead && row_info[r].endhead)) &&
2987                             !row_info[r].caption) {
2988                                 ret += xhtmlRow(xs, r, runparams, true);
2989                         }
2990                 }
2991                 xs << html::EndTag("thead") << html::CR();
2992         }
2993         // output footer info
2994         bool const havelastfoot = haveLTLastFoot(false);
2995         // as before.
2996         bool const havefoot = !havelastfoot && haveLTFoot(false);
2997         if (havefoot || havelastfoot) {
2998                 xs << html::StartTag("tfoot") << html::CR();
2999                 for (row_type r = 0; r < nrows(); ++r) {
3000                         if (((havelastfoot && row_info[r].endlastfoot) ||
3001                              (havefoot && row_info[r].endfoot)) &&
3002                             !row_info[r].caption) {
3003                                 ret += xhtmlRow(xs, r, runparams);
3004                         }
3005                 }
3006                 xs << html::EndTag("tfoot") << html::CR();
3007         }
3008
3009         xs << html::StartTag("tbody") << html::CR();
3010         for (row_type r = 0; r < nrows(); ++r) {
3011                 if (isValidRow(r)) {
3012                         ret += xhtmlRow(xs, r, runparams);
3013                 }
3014         }
3015         xs << html::EndTag("tbody")
3016            << html::CR()
3017            << html::EndTag("table")
3018            << html::CR();
3019         if (is_long_tabular)
3020                 xs << html::EndTag("div") << html::CR();
3021         return ret;
3022 }
3023
3024
3025 bool Tabular::plaintextTopHLine(odocstream & os, row_type row,
3026                                    vector<unsigned int> const & clen) const
3027 {
3028         idx_type const fcell = getFirstCellInRow(row);
3029         idx_type const n = numberOfCellsInRow(row) + fcell;
3030         idx_type tmp = 0;
3031
3032         for (idx_type i = fcell; i < n; ++i) {
3033                 if (topLine(i)) {
3034                         ++tmp;
3035                         break;
3036                 }
3037         }
3038         if (!tmp)
3039                 return false;
3040
3041         char_type ch;
3042         for (idx_type i = fcell; i < n; ++i) {
3043                 if (topLine(i)) {
3044                         if (leftLine(i))
3045                                 os << "+-";
3046                         else
3047                                 os << "--";
3048                         ch = '-';
3049                 } else {
3050                         os << "  ";
3051                         ch = ' ';
3052                 }
3053                 col_type column = cellColumn(i);
3054                 int len = clen[column];
3055                 while (column < ncols() - 1
3056                        && isPartOfMultiColumn(row, ++column))
3057                         len += clen[column] + 4;
3058                 os << docstring(len, ch);
3059                 if (topLine(i)) {
3060                         if (rightLine(i))
3061                                 os << "-+";
3062                         else
3063                                 os << "--";
3064                 } else {
3065                         os << "  ";
3066                 }
3067         }
3068         os << endl;
3069         return true;
3070 }
3071
3072
3073 bool Tabular::plaintextBottomHLine(odocstream & os, row_type row,
3074                                       vector<unsigned int> const & clen) const
3075 {
3076         idx_type const fcell = getFirstCellInRow(row);
3077         idx_type const n = numberOfCellsInRow(row) + fcell;
3078         idx_type tmp = 0;
3079
3080         for (idx_type i = fcell; i < n; ++i) {
3081                 if (bottomLine(i)) {
3082                         ++tmp;
3083                         break;
3084                 }
3085         }
3086         if (!tmp)
3087                 return false;
3088
3089         char_type ch;
3090         for (idx_type i = fcell; i < n; ++i) {
3091                 if (bottomLine(i)) {
3092                         if (leftLine(i))
3093                                 os << "+-";
3094                         else
3095                                 os << "--";
3096                         ch = '-';
3097                 } else {
3098                         os << "  ";
3099                         ch = ' ';
3100                 }
3101                 col_type column = cellColumn(i);
3102                 int len = clen[column];
3103                 while (column < ncols() - 1 && isPartOfMultiColumn(row, ++column))
3104                         len += clen[column] + 4;
3105                 os << docstring(len, ch);
3106                 if (bottomLine(i)) {
3107                         if (rightLine(i))
3108                                 os << "-+";
3109                         else
3110                                 os << "--";
3111                 } else {
3112                         os << "  ";
3113                 }
3114         }
3115         os << endl;
3116         return true;
3117 }
3118
3119
3120 void Tabular::plaintextPrintCell(odocstream & os,
3121                                OutputParams const & runparams,
3122                                idx_type cell, row_type row, col_type column,
3123                                vector<unsigned int> const & clen,
3124                                bool onlydata) const
3125 {
3126         odocstringstream sstr;
3127         cellInset(cell)->plaintext(sstr, runparams);
3128
3129         if (onlydata) {
3130                 os << sstr.str();
3131                 return;
3132         }
3133
3134         if (leftLine(cell))
3135                 os << "| ";
3136         else
3137                 os << "  ";
3138
3139         unsigned int len1 = sstr.str().length();
3140         unsigned int len2 = clen[column];
3141         while (column < ncols() - 1 && isPartOfMultiColumn(row, ++column))
3142                 len2 += clen[column] + 4;
3143         len2 -= len1;
3144
3145         switch (getAlignment(cell)) {
3146         default:
3147         case LYX_ALIGN_LEFT:
3148                 len1 = 0;
3149                 break;
3150         case LYX_ALIGN_RIGHT:
3151                 len1 = len2;
3152                 len2 = 0;
3153                 break;
3154         case LYX_ALIGN_CENTER:
3155                 len1 = len2 / 2;
3156                 len2 -= len1;
3157                 break;
3158         }
3159
3160         os << docstring(len1, ' ') << sstr.str()
3161            << docstring(len2, ' ');
3162
3163         if (rightLine(cell))
3164                 os << " |";
3165         else
3166                 os << "  ";
3167 }
3168
3169
3170 void Tabular::plaintext(odocstream & os,
3171                            OutputParams const & runparams, int const depth,
3172                            bool onlydata, char_type delim) const
3173 {
3174         // first calculate the width of the single columns
3175         vector<unsigned int> clen(ncols());
3176
3177         if (!onlydata) {
3178                 // first all non multicolumn cells!
3179                 for (col_type c = 0; c < ncols(); ++c) {
3180                         clen[c] = 0;
3181                         for (row_type r = 0; r < nrows(); ++r) {
3182                                 idx_type cell = cellIndex(r, c);
3183                                 if (isMultiColumn(cell))
3184                                         continue;
3185                                 odocstringstream sstr;
3186                                 cellInset(cell)->plaintext(sstr, runparams);
3187                                 if (clen[c] < sstr.str().length())
3188                                         clen[c] = sstr.str().length();
3189                         }
3190                 }
3191                 // then all multicolumn cells!
3192                 for (col_type c = 0; c < ncols(); ++c) {
3193                         for (row_type r = 0; r < nrows(); ++r) {
3194                                 idx_type cell = cellIndex(r, c);
3195                                 if (cell_info[r][c].multicolumn != CELL_BEGIN_OF_MULTICOLUMN)
3196                                         continue;
3197                                 odocstringstream sstr;
3198                                 cellInset(cell)->plaintext(sstr, runparams);
3199                                 int len = int(sstr.str().length());
3200                                 idx_type const n = columnSpan(cell);
3201                                 for (col_type k = c; len > 0 && k < c + n - 1; ++k)
3202                                         len -= clen[k];
3203                                 if (len > int(clen[c + n - 1]))
3204                                         clen[c + n - 1] = len;
3205                         }
3206                 }
3207         }
3208         idx_type cell = 0;
3209         for (row_type r = 0; r < nrows(); ++r) {
3210                 if (!onlydata && plaintextTopHLine(os, r, clen))
3211                         os << docstring(depth * 2, ' ');
3212                 for (col_type c = 0; c < ncols(); ++c) {
3213                         if (isPartOfMultiColumn(r, c) || isPartOfMultiRow(r,c))
3214                                 continue;
3215                         if (onlydata && c > 0)
3216                                 // we don't use operator<< for single UCS4 character.
3217                                 // see explanation in docstream.h
3218                                 os.put(delim);
3219                         plaintextPrintCell(os, runparams, cell, r, c, clen, onlydata);
3220                         ++cell;
3221                 }
3222                 os << endl;
3223                 if (!onlydata) {
3224                         os << docstring(depth * 2, ' ');
3225                         if (plaintextBottomHLine(os, r, clen))
3226                                 os << docstring(depth * 2, ' ');
3227                 }
3228         }
3229 }
3230
3231
3232 shared_ptr<InsetTableCell> Tabular::cellInset(idx_type cell) const
3233 {
3234         return cell_info[cellRow(cell)][cellColumn(cell)].inset;
3235 }
3236
3237
3238 shared_ptr<InsetTableCell> Tabular::cellInset(row_type row,
3239                                                col_type column) const
3240 {
3241         return cell_info[row][column].inset;
3242 }
3243
3244
3245 void Tabular::setCellInset(row_type row, col_type column,
3246                               shared_ptr<InsetTableCell> ins) const
3247 {
3248         CellData & cd = cell_info[row][column];
3249         cd.inset = ins;
3250 }
3251
3252
3253 void Tabular::validate(LaTeXFeatures & features) const
3254 {
3255         features.require("NeedTabularnewline");
3256         if (use_booktabs)
3257                 features.require("booktabs");
3258         if (is_long_tabular)
3259                 features.require("longtable");
3260         if (needRotating())
3261                 features.require("rotating");
3262         for (idx_type cell = 0; cell < numberofcells; ++cell) {
3263                 if (isMultiRow(cell))
3264                         features.require("multirow");
3265                 if (getVAlignment(cell) != LYX_VALIGN_TOP
3266                     || !getPWidth(cell).zero())
3267                         features.require("array");
3268                 cellInset(cell)->validate(features);
3269         }
3270 }
3271
3272
3273 Tabular::BoxType Tabular::useParbox(idx_type cell) const
3274 {
3275         ParagraphList const & parlist = cellInset(cell)->paragraphs();
3276         ParagraphList::const_iterator cit = parlist.begin();
3277         ParagraphList::const_iterator end = parlist.end();
3278
3279         for (; cit != end; ++cit)
3280                 for (int i = 0; i < cit->size(); ++i)
3281                         if (cit->isNewline(i))
3282                                 return BOX_PARBOX;
3283
3284         return BOX_NONE;
3285 }
3286
3287
3288 /////////////////////////////////////////////////////////////////////
3289 //
3290 // InsetTableCell
3291 //
3292 /////////////////////////////////////////////////////////////////////
3293
3294 InsetTableCell::InsetTableCell(Buffer * buf)
3295         : InsetText(buf, InsetText::PlainLayout), isFixedWidth(false),
3296           contentAlign(LYX_ALIGN_CENTER)
3297 {}
3298
3299
3300 bool InsetTableCell::forcePlainLayout(idx_type) const
3301 {
3302         return !isFixedWidth;
3303 }
3304
3305
3306 bool InsetTableCell::allowParagraphCustomization(idx_type) const
3307 {
3308         return isFixedWidth;
3309 }
3310
3311
3312 bool InsetTableCell::getStatus(Cursor & cur, FuncRequest const & cmd,
3313         FuncStatus & status) const
3314 {
3315         bool enabled = true;
3316         switch (cmd.action()) {
3317         case LFUN_LAYOUT:
3318                 enabled = !forcePlainLayout();
3319                 break;
3320         case LFUN_LAYOUT_PARAGRAPH:
3321                 enabled = allowParagraphCustomization();
3322                 break;
3323
3324         case LFUN_MATH_DISPLAY:
3325                 if (!hasFixedWidth()) {
3326                         enabled = false;
3327                         break;
3328                 } //fall-through
3329         default:
3330                 return InsetText::getStatus(cur, cmd, status);
3331         }
3332         status.setEnabled(enabled);
3333         return true;
3334 }
3335
3336 docstring InsetTableCell::asString(bool intoInsets) 
3337 {
3338         docstring retval;
3339         if (paragraphs().empty())
3340                 return retval;
3341         ParagraphList::const_iterator it = paragraphs().begin();
3342         ParagraphList::const_iterator en = paragraphs().end();
3343         bool first = true;
3344         for (; it != en; ++it) {
3345                 if (!first)
3346                         retval += "\n";
3347                 else
3348                         first = false;
3349                 retval += it->asString(intoInsets ? AS_STR_INSETS : AS_STR_NONE);
3350         }
3351         return retval;
3352 }
3353
3354
3355 docstring InsetTableCell::xhtml(XHTMLStream & xs, OutputParams const & rp) const
3356 {
3357         if (!isFixedWidth)
3358                 return InsetText::insetAsXHTML(xs, rp, InsetText::JustText);
3359         return InsetText::xhtml(xs, rp);
3360 }
3361
3362
3363
3364 /////////////////////////////////////////////////////////////////////
3365 //
3366 // InsetTabular
3367 //
3368 /////////////////////////////////////////////////////////////////////
3369
3370 InsetTabular::InsetTabular(Buffer * buf, row_type rows,
3371                            col_type columns)
3372         : Inset(buf), tabular(buf, max(rows, row_type(1)), max(columns, col_type(1))), scx_(0), 
3373         rowselect_(false), colselect_(false)
3374 {
3375 }
3376
3377
3378 InsetTabular::InsetTabular(InsetTabular const & tab)
3379         : Inset(tab), tabular(tab.tabular),  scx_(0)
3380 {
3381 }
3382
3383
3384 InsetTabular::~InsetTabular()
3385 {
3386         hideDialogs("tabular", this);
3387 }
3388
3389
3390 void InsetTabular::setBuffer(Buffer & buf)
3391 {
3392         tabular.setBuffer(buf);
3393         Inset::setBuffer(buf);
3394 }
3395
3396
3397 bool InsetTabular::insetAllowed(InsetCode code) const
3398 {
3399         switch (code) {
3400         case FLOAT_CODE:
3401         case MARGIN_CODE:
3402         case MATHMACRO_CODE:
3403         case WRAP_CODE:
3404                 return false;
3405
3406         case CAPTION_CODE:
3407                 return tabular.is_long_tabular;
3408
3409         default:
3410                 return true;
3411         }
3412 }
3413
3414
3415 void InsetTabular::write(ostream & os) const
3416 {
3417         os << "Tabular" << endl;
3418         tabular.write(os);
3419 }
3420
3421
3422 string InsetTabular::contextMenu(BufferView const &, int, int) const
3423 {
3424         // FIXME: depending on the selection state,
3425         // we could offer a different menu.
3426         return cell(0)->contextMenuName() + ";" + contextMenuName();
3427 }
3428
3429
3430 string InsetTabular::contextMenuName() const
3431 {
3432         return "context-tabular";
3433 }
3434
3435
3436 void InsetTabular::read(Lexer & lex)
3437 {
3438         //bool const old_format = (lex.getString() == "\\LyXTable");
3439
3440         tabular.read(lex);
3441
3442         //if (old_format)
3443         //      return;
3444
3445         lex.next();
3446         string token = lex.getString();
3447         while (lex && token != "\\end_inset") {
3448                 lex.next();
3449                 token = lex.getString();
3450         }
3451         if (!lex)
3452                 lex.printError("Missing \\end_inset at this point. ");
3453 }
3454
3455
3456 int InsetTabular::rowFromY(Cursor & cur, int y) const
3457 {
3458         // top y coordinate of tabular
3459         int h = yo(cur.bv()) - tabular.rowAscent(0) + offset_valign_;
3460         row_type r = 0;
3461         for (; r < tabular.nrows() && y > h; ++r)
3462                 h += tabular.rowAscent(r) + tabular.rowDescent(r)
3463                         + tabular.interRowSpace(r);
3464
3465         return r - 1;
3466 }
3467
3468
3469 int InsetTabular::columnFromX(Cursor & cur, int x) const
3470 {
3471         // left x coordinate of tabular
3472         int w = xo(cur.bv()) + ADD_TO_TABULAR_WIDTH;
3473         col_type c = 0;
3474         for (; c < tabular.ncols() && x > w; ++c)
3475                 w += tabular.cellWidth(c);
3476         return c - 1;
3477 }
3478
3479
3480 void InsetTabular::metrics(MetricsInfo & mi, Dimension & dim) const
3481 {
3482         //lyxerr << "InsetTabular::metrics: " << mi.base.bv << " width: " <<
3483         //      mi.base.textwidth << "\n";
3484         if (!mi.base.bv) {
3485                 LYXERR0("need bv");
3486                 LASSERT(false, /**/);
3487         }
3488
3489         for (row_type r = 0; r < tabular.nrows(); ++r) {
3490                 int maxasc = 0;
3491                 int maxdes = 0;
3492                 for (col_type c = 0; c < tabular.ncols(); ++c) {
3493                         if (tabular.isPartOfMultiColumn(r, c)
3494                                 || tabular.isPartOfMultiRow(r, c))
3495                                 // multicolumn or multirow cell, but not first one
3496                                 continue;
3497                         idx_type const cell = tabular.cellIndex(r, c);
3498                         Dimension dim;
3499                         MetricsInfo m = mi;
3500                         Length const p_width = tabular.getPWidth(cell);
3501                         if (!p_width.zero())
3502                                 m.base.textwidth = p_width.inPixels(mi.base.textwidth);
3503                         tabular.cellInset(cell)->metrics(m, dim);
3504                         if (!p_width.zero())
3505                                 dim.wid = m.base.textwidth;
3506                         tabular.cellInfo(cell).width = dim.wid + 2 * WIDTH_OF_LINE 
3507                                 + tabular.interColumnSpace(cell);
3508
3509                         // FIXME(?): do we need a second metrics call?
3510                         TextMetrics const & tm = 
3511                                 mi.base.bv->textMetrics(tabular.cellInset(cell)->getText(0));
3512
3513                         // determine horizontal offset because of decimal align (if necessary)
3514                         int decimal_width = 0;
3515                         if (tabular.getAlignment(cell) == LYX_ALIGN_DECIMAL) {
3516                                 InsetTableCell tail = InsetTableCell(*tabular.cellInset(cell).get());
3517                                 tail.setBuffer(tabular.buffer());
3518                                 // we need to set macrocontext position everywhere
3519                                 // otherwise we crash with nested insets (e.g. footnotes)
3520                                 // after decimal point
3521                                 DocIterator dit = tabular.cellInset(cell)->getText(0)->macrocontextPosition();
3522                                 dit.pop_back();
3523                                 dit.push_back(CursorSlice(tail));
3524                                 tail.setMacrocontextPositionRecursive(dit);
3525
3526                                 // remove text leading decimal point
3527                                 docstring const align_d = tabular.column_info[c].decimal_point;
3528                                 dit = separatorPos(&tail, align_d);
3529
3530                                 pit_type const psize = tail.paragraphs().front().size();
3531                                 if (dit) {
3532                                         tail.paragraphs().front().eraseChars(0,
3533                                                 dit.pos() < psize ? dit.pos() + 1 : psize, false);
3534                                         Dimension dim1;
3535                                         tail.metrics(m, dim1);
3536                                         decimal_width = dim1.width();
3537                                 }
3538                         }
3539                         tabular.cell_info[r][c].decimal_hoffset = tm.width() - decimal_width;
3540                         tabular.cell_info[r][c].decimal_width = decimal_width;
3541
3542                         // with LYX_VALIGN_BOTTOM the descent is relative to the last par
3543                         // = descent of text in last par + TEXT_TO_INSET_OFFSET:
3544                         int const lastpardes = tm.last().second->descent()
3545                                 + TEXT_TO_INSET_OFFSET;
3546                         int offset = 0;
3547                         switch (tabular.getVAlignment(cell)) { 
3548                                 case Tabular::LYX_VALIGN_TOP:
3549                                         break; 
3550                                 case Tabular::LYX_VALIGN_MIDDLE:
3551                                         offset = -(dim.des - lastpardes)/2; 
3552                                         break; 
3553                                 case Tabular::LYX_VALIGN_BOTTOM:
3554                                         offset = -(dim.des - lastpardes); 
3555                                         break;
3556                         }
3557                         tabular.cell_info[r][c].voffset = offset;
3558                         maxasc = max(maxasc, dim.asc - offset);
3559                         maxdes = max(maxdes, dim.des + offset);
3560                 }
3561                 int const top_space = tabular.row_info[r].top_space_default ?
3562                         default_line_space :
3563                         tabular.row_info[r].top_space.inPixels(mi.base.textwidth);
3564                 tabular.setRowAscent(r, maxasc + ADD_TO_HEIGHT + top_space);
3565                 int const bottom_space = tabular.row_info[r].bottom_space_default ?
3566                         default_line_space :
3567                         tabular.row_info[r].bottom_space.inPixels(mi.base.textwidth);
3568                 tabular.setRowDescent(r, maxdes + ADD_TO_HEIGHT + bottom_space);
3569         }
3570
3571         // for top-alignment the first horizontal table line must be exactly at
3572         // the position of the base line of the surrounding text line
3573         // for bottom alignment, the same is for the last table line
3574         switch (tabular.tabular_valignment) {
3575         case Tabular::LYX_VALIGN_BOTTOM:
3576                 offset_valign_ = tabular.rowAscent(0) - tabular.height();
3577                 break;
3578         case Tabular::LYX_VALIGN_MIDDLE:
3579                 offset_valign_ = (- tabular.height()) / 2 + tabular.rowAscent(0);
3580                 break;
3581         case Tabular::LYX_VALIGN_TOP:
3582                 offset_valign_ = tabular.rowAscent(0);
3583                 break;
3584         }
3585
3586         tabular.updateColumnWidths();
3587         dim.asc = tabular.rowAscent(0) - offset_valign_;        
3588         dim.des = tabular.height() - dim.asc;
3589         dim.wid = tabular.width() + 2 * ADD_TO_TABULAR_WIDTH;
3590 }
3591
3592
3593 bool InsetTabular::isCellSelected(Cursor & cur, row_type row, col_type col) 
3594         const
3595 {
3596         if (&cur.inset() == this && cur.selection()) {
3597                 if (cur.selIsMultiCell()) {
3598                         row_type rs, re;
3599                         col_type cs, ce;
3600                         getSelection(cur, rs, re, cs, ce);
3601                         
3602                         idx_type const cell = tabular.cellIndex(row, col);
3603                         col_type const cspan = tabular.columnSpan(cell);
3604                         row_type const rspan = tabular.rowSpan(cell);
3605                         if (col + cspan - 1 >= cs && col <= ce 
3606                                 && row + rspan - 1 >= rs && row <= re)
3607                                 return true;
3608                 } else 
3609                         if (col == tabular.cellColumn(cur.idx()) 
3610                                 && row == tabular.cellRow(cur.idx())) {
3611                         CursorSlice const & beg = cur.selBegin();
3612                         CursorSlice const & end = cur.selEnd();
3613
3614                         if ((end.lastpos() > 0 || end.lastpit() > 0)
3615                                   && end.pos() == end.lastpos() && beg.pos() == 0
3616                                   && end.pit() == end.lastpit() && beg.pit() == 0)
3617                                 return true;
3618                 }
3619         }
3620         return false;
3621 }
3622
3623
3624 void InsetTabular::draw(PainterInfo & pi, int x, int y) const
3625 {
3626         x += scx_ + ADD_TO_TABULAR_WIDTH;
3627
3628         BufferView * bv = pi.base.bv;
3629         Cursor & cur = pi.base.bv->cursor();
3630         resetPos(cur);
3631
3632         // FIXME: As the full background is painted in drawBackground(),
3633         // we have no choice but to do a full repaint for the Text cells.
3634         pi.full_repaint = true;
3635
3636         bool const original_selection_state = pi.selected;
3637
3638         idx_type idx = 0;
3639         first_visible_cell = Tabular::npos;
3640
3641         int yy = y + offset_valign_;
3642         for (row_type r = 0; r < tabular.nrows(); ++r) {
3643                 int nx = x;
3644                 for (col_type c = 0; c < tabular.ncols(); ++c) {
3645                         if (tabular.isPartOfMultiColumn(r, c))
3646                                 continue;
3647                         
3648                         idx = tabular.cellIndex(r, c);
3649                         
3650                         if (tabular.isPartOfMultiRow(r, c)) {
3651                                 nx += tabular.cellWidth(idx);
3652                                 continue;
3653                         }
3654
3655                         if (first_visible_cell == Tabular::npos)
3656                                 first_visible_cell = idx;
3657
3658                         pi.selected |= isCellSelected(cur, r, c);
3659                         int const cx = nx + tabular.textHOffset(idx);
3660                         int const cy = yy + tabular.textVOffset(idx);
3661                         // Cache the Inset position.
3662                         bv->coordCache().insets().add(cell(idx).get(), cx, cy);
3663                         cell(idx)->draw(pi, cx, cy);
3664                         drawCellLines(pi, nx, yy, r, idx);
3665                         nx += tabular.cellWidth(idx);
3666                         pi.selected = original_selection_state;
3667                 }
3668
3669                 if (r + 1 < tabular.nrows())
3670                         yy += tabular.rowDescent(r) + tabular.rowAscent(r + 1) 
3671                                 + tabular.interRowSpace(r + 1);
3672         }
3673 }
3674
3675
3676 void InsetTabular::drawBackground(PainterInfo & pi, int x, int y) const
3677 {
3678         x += scx_ + ADD_TO_TABULAR_WIDTH;
3679         y += offset_valign_ - tabular.rowAscent(0);
3680         pi.pain.fillRectangle(x, y, tabular.width(), tabular.height(),
3681                 pi.backgroundColor(this));
3682 }
3683
3684
3685 void InsetTabular::drawSelection(PainterInfo & pi, int x, int y) const
3686 {
3687         Cursor & cur = pi.base.bv->cursor();
3688         resetPos(cur);
3689
3690         x += scx_ + ADD_TO_TABULAR_WIDTH;
3691
3692         if (!cur.selection())
3693                 return;
3694         if (&cur.inset() != this)
3695                 return;
3696
3697         //resetPos(cur);
3698
3699         bool const full_cell_selected = isCellSelected(cur,
3700                 tabular.cellRow(cur.idx()), tabular.cellColumn(cur.idx()));
3701
3702         if (cur.selIsMultiCell() || full_cell_selected) {
3703                 for (row_type r = 0; r < tabular.nrows(); ++r) {
3704                         int xx = x;
3705                         for (col_type c = 0; c < tabular.ncols(); ++c) {
3706                                 if (tabular.isPartOfMultiColumn(r, c))
3707                                         continue;
3708
3709                                 idx_type const cell = tabular.cellIndex(r, c);
3710
3711                                 if (tabular.isPartOfMultiRow(r, c)) {
3712                                         xx += tabular.cellWidth(cell);
3713                                         continue;
3714                                 }
3715                                 int const w = tabular.cellWidth(cell);
3716                                 int const h = tabular.cellHeight(cell);
3717                                 int const yy = y - tabular.rowAscent(r) + offset_valign_;
3718                                 if (isCellSelected(cur, r, c))
3719                                         pi.pain.fillRectangle(xx, yy, w, h, Color_selection);
3720                                 xx += w;
3721                         }
3722                         if (r + 1 < tabular.nrows())
3723                                 y += tabular.rowDescent(r) + tabular.rowAscent(r + 1)
3724                                      + tabular.interRowSpace(r + 1);
3725                 }
3726
3727         } 
3728         // FIXME: This code has no effect because InsetTableCell does not handle
3729         // drawSelection other than the trivial implementation in Inset.
3730         //else {
3731         //      x += cellXPos(cur.idx());
3732         //      x += tabular.textHOffset(cur.idx());
3733         //      cell(cur.idx())->drawSelection(pi, x, 0 /* ignored */);
3734         //}
3735 }
3736
3737
3738 void InsetTabular::drawCellLines(PainterInfo & pi, int x, int y,
3739                                  row_type row, idx_type cell) const
3740 {
3741         y -= tabular.rowAscent(row);
3742         int const w = tabular.cellWidth(cell);
3743         int const h = tabular.cellHeight(cell);
3744         Color const linecolor = pi.textColor(Color_tabularline);
3745         Color const gridcolor = pi.textColor(Color_tabularonoffline);
3746
3747         // Top
3748         bool drawline = tabular.topLine(cell)
3749                 || (row > 0 && tabular.bottomLine(tabular.cellAbove(cell)));
3750         pi.pain.line(x, y, x + w, y,
3751                 drawline ? linecolor : gridcolor,
3752                 drawline ? Painter::line_solid : Painter::line_onoffdash);
3753
3754         // Bottom
3755         drawline = tabular.bottomLine(cell);
3756         pi.pain.line(x, y + h, x + w, y + h,
3757                 drawline ? linecolor : gridcolor,
3758                 drawline ? Painter::line_solid : Painter::line_onoffdash);
3759
3760         // Left
3761         col_type const col = tabular.cellColumn(cell);
3762         drawline = tabular.leftLine(cell)
3763                 || (col > 0 && tabular.rightLine(tabular.cellIndex(row, col - 1)));
3764         pi.pain.line(x, y, x, y + h,
3765                 drawline ? linecolor : gridcolor,
3766                 drawline ? Painter::line_solid : Painter::line_onoffdash);
3767
3768         // Right
3769         x -= tabular.interColumnSpace(cell);
3770         drawline = tabular.rightLine(cell)
3771                    || (col + 1 < tabular.ncols()
3772                        && tabular.leftLine(tabular.cellIndex(row, col + 1)));
3773         pi.pain.line(x + w, y, x + w, y + h,
3774                 drawline ? linecolor : gridcolor,
3775                 drawline ? Painter::line_solid : Painter::line_onoffdash);
3776 }
3777
3778
3779 void InsetTabular::edit(Cursor & cur, bool front, EntryDirection)
3780 {
3781         //lyxerr << "InsetTabular::edit: " << this << endl;
3782         cur.finishUndo();
3783         cur.setSelection(false);
3784         cur.push(*this);
3785         if (front) {
3786                 if (isRightToLeft(cur))
3787                         cur.idx() = tabular.getLastCellInRow(0);
3788                 else
3789                         cur.idx() = 0;
3790                 cur.pit() = 0;
3791                 cur.pos() = 0;
3792         } else {
3793                 if (isRightToLeft(cur))
3794                         cur.idx() = tabular.getFirstCellInRow(tabular.nrows() - 1);
3795                 else
3796                         cur.idx() = tabular.numberofcells - 1;
3797                 cur.pit() = 0;
3798                 cur.pos() = cur.lastpos(); // FIXME crude guess
3799         }
3800         cur.setCurrentFont();
3801         // FIXME: this accesses the position cache before it is initialized
3802         //resetPos(cur);
3803         //cur.bv().fitCursor();
3804 }
3805
3806
3807 void InsetTabular::updateBuffer(ParIterator const & it, UpdateType utype)
3808 {
3809         // In a longtable, tell captions what the current float is
3810         Counters & cnts = buffer().masterBuffer()->params().documentClass().counters();
3811         string const saveflt = cnts.current_float();
3812         if (tabular.is_long_tabular)
3813                 cnts.current_float("table");
3814
3815         ParIterator it2 = it;
3816         it2.forwardPos();
3817         size_t const end = it2.nargs();
3818         for ( ; it2.idx() < end; it2.top().forwardIdx())
3819                 buffer().updateBuffer(it2, utype);
3820
3821         //reset afterwards
3822         if (tabular.is_long_tabular)
3823                 cnts.current_float(saveflt);
3824 }
3825
3826
3827 void InsetTabular::addToToc(DocIterator const & cpit) const
3828 {
3829         DocIterator dit = cpit;
3830         dit.forwardPos();
3831         size_t const end = dit.nargs();
3832         for ( ; dit.idx() < end; dit.top().forwardIdx())
3833                 cell(dit.idx())->addToToc(dit);
3834 }
3835
3836
3837 void InsetTabular::doDispatch(Cursor & cur, FuncRequest & cmd)
3838 {
3839         LYXERR(Debug::DEBUG, "# InsetTabular::doDispatch: cmd: " << cmd
3840                              << "\n  cur:" << cur);
3841         CursorSlice sl = cur.top();
3842         Cursor & bvcur = cur.bv().cursor();
3843
3844         FuncCode const act = cmd.action();
3845         
3846         switch (act) {
3847
3848         case LFUN_MOUSE_PRESS: {
3849                 //lyxerr << "# InsetTabular::MousePress\n" << cur.bv().cursor() << endl;
3850                 // select row
3851                 if (cmd.x() < xo(cur.bv()) + ADD_TO_TABULAR_WIDTH
3852                         || cmd.x() > xo(cur.bv()) + tabular.width()) {
3853                         row_type r = rowFromY(cur, cmd.y());
3854                         cur.idx() = tabular.getFirstCellInRow(r);
3855                         cur.pos() = 0;
3856                         cur.resetAnchor();
3857                         cur.idx() = tabular.getLastCellInRow(r);
3858                         cur.pos() = cur.lastpos();
3859                         cur.setSelection(true);
3860                         bvcur = cur; 
3861                         rowselect_ = true;
3862                         break;
3863                 }
3864                 // select column
3865                 int const y0 = yo(cur.bv()) - tabular.rowAscent(0) + offset_valign_;
3866                 if (cmd.y() < y0 + ADD_TO_TABULAR_WIDTH 
3867                         || cmd.y() > y0 + tabular.height()) {
3868                         col_type c = columnFromX(cur, cmd.x());
3869                         cur.idx() = tabular.cellIndex(0, c);
3870                         cur.pos() = 0;
3871                         cur.resetAnchor();
3872                         cur.idx() = tabular.cellIndex(tabular.nrows() - 1, c);
3873                         cur.pos() = cur.lastpos();
3874                         cur.setSelection(true);
3875                         bvcur = cur; 
3876                         colselect_ = true;
3877                         break;
3878                 }
3879                 // do not reset cursor/selection if we have selected
3880                 // some cells (bug 2715).
3881                 if (cmd.button() == mouse_button::button3
3882                     && &bvcur.selBegin().inset() == this 
3883                     && bvcur.selIsMultiCell()) 
3884                         ;
3885                 else
3886                         // Let InsetTableCell do it
3887                         cell(cur.idx())->dispatch(cur, cmd);
3888                 break;
3889         }
3890         case LFUN_MOUSE_MOTION:
3891                 //lyxerr << "# InsetTabular::MouseMotion\n" << bvcur << endl;
3892                 if (cmd.button() == mouse_button::button1) {
3893                         // only accept motions to places not deeper nested than the real anchor
3894                         if (!bvcur.realAnchor().hasPart(cur)) {
3895                                 cur.undispatched();
3896                                 break;
3897                         }
3898                         // select (additional) row
3899                         if (rowselect_) {
3900                                 row_type r = rowFromY(cur, cmd.y());
3901                                 cur.idx() = tabular.getLastCellInRow(r);
3902                                 // we need to reset the cursor's pit and pos now, as the old ones
3903                                 // may no longer be valid.
3904                                 cur.pit() = 0;
3905                                 cur.pos() = 0;
3906                                 bvcur.setCursor(cur);
3907                                 bvcur.setSelection(true);
3908                                 break;
3909                         }
3910                         // select (additional) column
3911                         if (colselect_) {
3912                                 col_type c = columnFromX(cur, cmd.x());
3913                                 cur.idx() = tabular.cellIndex(tabular.nrows() - 1, c);
3914                                 // we need to reset the cursor's pit and pos now, as the old ones
3915                                 // may no longer be valid.
3916                                 cur.pit() = 0;
3917                                 cur.pos() = 0;
3918                                 bvcur.setCursor(cur);
3919                                 bvcur.setSelection(true);
3920                                 break;
3921                         }
3922                         // only update if selection changes
3923                         if (bvcur.idx() == cur.idx() &&
3924                                 !(bvcur.realAnchor().idx() == cur.idx() && bvcur.pos() != cur.pos()))
3925                                 cur.noScreenUpdate();
3926                         setCursorFromCoordinates(cur, cmd.x(), cmd.y());
3927                         bvcur.setCursor(cur);
3928                         bvcur.setSelection(true);
3929                         // if this is a multicell selection, we just set the cursor to
3930                         // the beginning of the cell's text.
3931                         if (bvcur.selIsMultiCell()) {
3932                                 bvcur.pit() = bvcur.lastpit();
3933                                 bvcur.pos() = bvcur.lastpos();
3934                         }
3935                 }
3936                 break;
3937
3938         case LFUN_MOUSE_RELEASE:
3939                 rowselect_ = false;
3940                 colselect_ = false;
3941                 break;
3942
3943         case LFUN_CELL_BACKWARD:
3944                 movePrevCell(cur);
3945                 cur.setSelection(false);
3946                 break;
3947
3948         case LFUN_CELL_FORWARD:
3949                 moveNextCell(cur);
3950                 cur.setSelection(false);
3951                 break;
3952
3953         case LFUN_CHAR_FORWARD_SELECT:
3954         case LFUN_CHAR_FORWARD:
3955         case LFUN_CHAR_BACKWARD_SELECT:
3956         case LFUN_CHAR_BACKWARD:
3957         case LFUN_CHAR_RIGHT_SELECT:
3958         case LFUN_CHAR_RIGHT:
3959         case LFUN_CHAR_LEFT_SELECT:
3960         case LFUN_CHAR_LEFT: 
3961         case LFUN_WORD_FORWARD:
3962         case LFUN_WORD_FORWARD_SELECT:
3963         case LFUN_WORD_BACKWARD:
3964         case LFUN_WORD_BACKWARD_SELECT:
3965         case LFUN_WORD_RIGHT:
3966         case LFUN_WORD_RIGHT_SELECT:
3967         case LFUN_WORD_LEFT:
3968         case LFUN_WORD_LEFT_SELECT: {
3969                 // determine whether we move to next or previous cell, where to enter 
3970                 // the new cell from, and which command to "finish" (i.e., exit the
3971                 // inset) with:
3972                 bool next_cell;
3973                 EntryDirection entry_from = ENTRY_DIRECTION_IGNORE;
3974                 FuncCode finish_lfun;
3975
3976                 if (act == LFUN_CHAR_FORWARD 
3977                                 || act == LFUN_CHAR_FORWARD_SELECT
3978                                 || act == LFUN_WORD_FORWARD
3979                                 || act == LFUN_WORD_FORWARD_SELECT) {
3980                         next_cell = true;
3981                         finish_lfun = LFUN_FINISHED_FORWARD;
3982                 }
3983                 else if (act == LFUN_CHAR_BACKWARD
3984                                 || act == LFUN_CHAR_BACKWARD_SELECT
3985                                 || act == LFUN_WORD_BACKWARD
3986                                 || act == LFUN_WORD_BACKWARD_SELECT) {
3987                         next_cell = false;
3988                         finish_lfun = LFUN_FINISHED_BACKWARD;
3989                 }
3990                 // LEFT or RIGHT commands --- the interpretation will depend on the 
3991                 // table's direction.
3992                 else {
3993                         bool const right = act == LFUN_CHAR_RIGHT
3994                                 || act == LFUN_CHAR_RIGHT_SELECT
3995                                 || act == LFUN_WORD_RIGHT
3996                                 || act == LFUN_WORD_RIGHT_SELECT;
3997                         next_cell = isRightToLeft(cur) != right;
3998                         
3999                         if (lyxrc.visual_cursor)
4000                                 entry_from = right ? ENTRY_DIRECTION_LEFT:ENTRY_DIRECTION_RIGHT;
4001
4002                         finish_lfun = right ? LFUN_FINISHED_RIGHT : LFUN_FINISHED_LEFT;
4003                 }
4004
4005                 bool const select =     act == LFUN_CHAR_FORWARD_SELECT 
4006                     || act == LFUN_CHAR_BACKWARD_SELECT
4007                     || act == LFUN_CHAR_RIGHT_SELECT
4008                     || act == LFUN_CHAR_LEFT_SELECT
4009                         || act == LFUN_WORD_FORWARD_SELECT
4010                         || act == LFUN_WORD_RIGHT_SELECT
4011                         || act == LFUN_WORD_BACKWARD_SELECT
4012                         || act == LFUN_WORD_LEFT_SELECT;
4013
4014                 // If we have a multicell selection or we're 
4015                 // not doing some LFUN_*_SELECT thing anyway...
4016                 if (!cur.selIsMultiCell() || !select) {
4017                         col_type const c = tabular.cellColumn(cur.idx());
4018                         row_type const r = tabular.cellRow(cur.idx());
4019                         // Are we trying to select the whole cell and is the whole cell 
4020                         // not yet selected?
4021                         bool const select_whole = select && !isCellSelected(cur, r, c) &&
4022                                 ((next_cell && cur.pit() == cur.lastpit() 
4023                                 && cur.pos() == cur.lastpos())
4024                                 || (!next_cell && cur.pit() == 0 && cur.pos() == 0));
4025
4026                         bool const empty_cell = cur.lastpos() == 0 && cur.lastpit() == 0;
4027
4028                         // ...try to dispatch to the cell's inset.
4029                         cell(cur.idx())->dispatch(cur, cmd);
4030
4031                         // When we already have a selection we want to select the whole cell
4032                         // before going to the next cell.
4033                         if (select_whole && !empty_cell){
4034                                 getText(cur.idx())->selectAll(cur);
4035                                 cur.dispatched();
4036                                 break;
4037                         }
4038
4039                         // FIXME: When we support the selection of an empty cell, remove 
4040                         // the !empty_cell from this condition. For now we jump to the next
4041                         // cell if the current cell is empty.
4042                         if (cur.result().dispatched() && !empty_cell)
4043                                 break;
4044                 }
4045
4046                 // move to next/prev cell, as appropriate
4047                 // note that we will always do this if we're selecting and we have
4048                 // a multicell selection
4049                 LYXERR(Debug::RTL, "entering " << (next_cell ? "next" : "previous")
4050                         << " cell from: " << int(entry_from));
4051                 if (next_cell)
4052                         moveNextCell(cur, entry_from);
4053                 else
4054                         movePrevCell(cur, entry_from);
4055                 // if we're exiting the table, call the appropriate FINISHED lfun
4056                 if (sl == cur.top())
4057                         cmd = FuncRequest(finish_lfun);
4058                 else
4059                         cur.dispatched();
4060
4061                 cur.screenUpdateFlags(Update::Force | Update::FitCursor);
4062                 break;
4063
4064         }
4065
4066         case LFUN_DOWN_SELECT:
4067         case LFUN_DOWN:
4068                 if (!(cur.selection() && cur.selIsMultiCell()))
4069                         cell(cur.idx())->dispatch(cur, cmd);
4070                 
4071                 cur.dispatched(); // override the cell's decision
4072                 if (sl == cur.top()) {
4073                         // if our Text didn't do anything to the cursor
4074                         // then we try to put the cursor into the cell below
4075                         // setting also the right targetX.
4076                         cur.selHandle(act == LFUN_DOWN_SELECT);
4077                         if (tabular.cellRow(cur.idx()) != tabular.nrows() - 1) {
4078                                 int const xtarget = cur.targetX();
4079                                 // WARNING: Once cur.idx() has been reset, the cursor is in
4080                                 // an inconsistent state until pos() has been set. Be careful
4081                                 // what you do with it!
4082                                 cur.idx() = tabular.cellBelow(cur.idx());
4083                                 cur.pit() = 0;
4084                                 TextMetrics const & tm =
4085                                         cur.bv().textMetrics(cell(cur.idx())->getText(0));
4086                                 cur.pos() = tm.x2pos(cur.pit(), 0, xtarget);
4087                                 cur.setCurrentFont();
4088                         }
4089                 }
4090                 if (sl == cur.top()) {
4091                         // we trick it to go to forward after leaving the
4092                         // tabular.
4093                         cmd = FuncRequest(LFUN_FINISHED_FORWARD);
4094                         cur.undispatched();
4095                 }
4096                 if (cur.selIsMultiCell()) {
4097                         cur.pit() = cur.lastpit();
4098                         cur.pos() = cur.lastpos();
4099                         cur.setCurrentFont();
4100                         return;
4101                 }
4102                 cur.screenUpdateFlags(Update::FitCursor);
4103                 break;
4104
4105         case LFUN_UP_SELECT:
4106         case LFUN_UP:
4107                 if (!(cur.selection() && cur.selIsMultiCell()))
4108                         cell(cur.idx())->dispatch(cur, cmd);
4109                 cur.dispatched(); // override the cell's decision
4110                 if (sl == cur.top()) {
4111                         // if our Text didn't do anything to the cursor
4112                         // then we try to put the cursor into the cell above
4113                         // setting also the right targetX.
4114                         cur.selHandle(act == LFUN_UP_SELECT);
4115                         if (tabular.cellRow(cur.idx()) != 0) {
4116                                 int const xtarget = cur.targetX();
4117                                 // WARNING: Once cur.idx() has been reset, the cursor is in
4118                                 // an inconsistent state until pos() has been set. Be careful
4119                                 // what you do with it!
4120                                 cur.idx() = tabular.cellAbove(cur.idx());
4121                                 cur.pit() = cur.lastpit();
4122                                 Text const * text = cell(cur.idx())->getText(0);
4123                                 TextMetrics const & tm = cur.bv().textMetrics(text);
4124                                 ParagraphMetrics const & pm =
4125                                         tm.parMetrics(cur.lastpit());
4126                                 cur.pos() = tm.x2pos(cur.pit(), pm.rows().size()-1, xtarget);
4127                                 cur.setCurrentFont();
4128                         }
4129                 }
4130                 if (sl == cur.top()) {
4131                         cmd = FuncRequest(LFUN_UP);
4132                         cur.undispatched();
4133                 }
4134                 if (cur.selIsMultiCell()) {
4135                         cur.pit() = 0;
4136                         cur.pos() = cur.lastpos();
4137                         cur.setCurrentFont();
4138                         return;
4139                 }
4140                 cur.screenUpdateFlags(Update::FitCursor);
4141                 break;
4142
4143 //      case LFUN_SCREEN_DOWN: {
4144 //              //if (hasSelection())
4145 //              //      cur.selection() = false;
4146 //              col_type const col = tabular.cellColumn(cur.idx());
4147 //              int const t =   cur.bv().top_y() + cur.bv().height();
4148 //              if (t < yo() + tabular.getHeightOfTabular()) {
4149 //                      cur.bv().scrollDocView(t, true);
4150 //                      cur.idx() = tabular.cellBelow(first_visible_cell) + col;
4151 //              } else {
4152 //                      cur.idx() = tabular.getFirstCellInRow(tabular.rows() - 1) + col;
4153 //              }
4154 //              cur.par() = 0;
4155 //              cur.pos() = 0;
4156 //              break;
4157 //      }
4158 //
4159 //      case LFUN_SCREEN_UP: {
4160 //              //if (hasSelection())
4161 //              //      cur.selection() = false;
4162 //              col_type const col = tabular.cellColumn(cur.idx());
4163 //              int const t =   cur.bv().top_y() + cur.bv().height();
4164 //              if (yo() < 0) {
4165 //                      cur.bv().scrollDocView(t, true);
4166 //                      if (yo() > 0)
4167 //                              cur.idx() = col;
4168 //                      else
4169 //                              cur.idx() = tabular.cellBelow(first_visible_cell) + col;
4170 //              } else {
4171 //                      cur.idx() = col;
4172 //              }
4173 //              cur.par() = cur.lastpar();
4174 //              cur.pos() = cur.lastpos();
4175 //              break;
4176 //      }
4177
4178         case LFUN_LAYOUT_TABULAR:
4179                 cur.bv().showDialog("tabular");
4180                 break;
4181
4182         case LFUN_INSET_MODIFY: {
4183                 string arg;
4184                 if (cmd.getArg(1) == "from-dialog")
4185                         arg = cmd.getArg(0) + to_utf8(cmd.argument().substr(19));
4186                 else
4187                         arg = to_utf8(cmd.argument());
4188                 if (!tabularFeatures(cur, arg))
4189                         cur.undispatched();
4190                 break;
4191         }
4192
4193         // insert file functions
4194         case LFUN_FILE_INSERT_PLAINTEXT_PARA:
4195         case LFUN_FILE_INSERT_PLAINTEXT:
4196                 // FIXME UNICODE
4197                 if (FileName::isAbsolute(to_utf8(cmd.argument()))) {
4198                         docstring const tmpstr = cur.bv().contentsOfPlaintextFile(
4199                                 FileName(to_utf8(cmd.argument())));
4200                         if (tmpstr.empty())
4201                                 break;
4202                         cur.recordUndoInset(INSERT_UNDO);
4203                         if (insertPlaintextString(cur.bv(), tmpstr, false)) {
4204                                 // content has been replaced,
4205                                 // so cursor might be invalid
4206                                 cur.pos() = cur.lastpos();
4207                                 cur.pit() = cur.lastpit();
4208                                 bvcur.setCursor(cur);
4209                         } else
4210                                 cur.undispatched();
4211                 }
4212                 break;
4213
4214         case LFUN_CUT:
4215                 if (cur.selIsMultiCell()) {
4216                         if (copySelection(cur)) {
4217                                 cur.recordUndoInset(DELETE_UNDO);
4218                                 cutSelection(cur);
4219                         }
4220                 } else
4221                         cell(cur.idx())->dispatch(cur, cmd);
4222                 break;
4223
4224         case LFUN_SELF_INSERT:
4225                 if (cur.selIsMultiCell()) {
4226                         cur.recordUndoInset(DELETE_UNDO);
4227                         cutSelection(cur);
4228                 }
4229                 cell(cur.idx())->dispatch(cur, cmd);
4230                 break;
4231
4232         case LFUN_CHAR_DELETE_BACKWARD:
4233         case LFUN_CHAR_DELETE_FORWARD:
4234                 if (cur.selIsMultiCell()) {
4235                         cur.recordUndoInset(DELETE_UNDO);
4236                         cutSelection(cur);
4237                 } else
4238                         cell(cur.idx())->dispatch(cur, cmd);
4239                 break;
4240
4241         case LFUN_COPY:
4242                 if (!cur.selection())
4243                         break;
4244                 if (cur.selIsMultiCell()) {
4245                         cur.finishUndo();
4246                         copySelection(cur);
4247                 } else
4248                         cell(cur.idx())->dispatch(cur, cmd);
4249                 break;
4250
4251         case LFUN_CLIPBOARD_PASTE:
4252         case LFUN_PRIMARY_SELECTION_PASTE: {
4253                 docstring const clip = (act == LFUN_CLIPBOARD_PASTE) ?
4254                         theClipboard().getAsText() :
4255                         theSelection().get();
4256                 if (clip.empty())
4257                         break;
4258                 // pass to InsertPlaintextString, but
4259                 // only if we have multi-cell content
4260                 if (clip.find_first_of(from_ascii("\t\n")) != docstring::npos) {
4261                         cur.recordUndoInset(INSERT_UNDO);
4262                         if (insertPlaintextString(cur.bv(), clip, false)) {
4263                                 // content has been replaced,
4264                                 // so cursor might be invalid
4265                                 cur.pos() = cur.lastpos();
4266                                 cur.pit() = cur.lastpit();
4267                                 bvcur.setCursor(cur);
4268                                 break;
4269                         }
4270                 }
4271                 // Let the cell handle normal text
4272                 cell(cur.idx())->dispatch(cur, cmd);
4273                 break;
4274         }
4275
4276         case LFUN_PASTE:
4277                 if (!tabularStackDirty()) {
4278                         if (!cur.selIsMultiCell())
4279                                 cell(cur.idx())->dispatch(cur, cmd);
4280                         break;
4281                 }
4282                 if (theClipboard().isInternal()) {
4283                         cur.recordUndoInset(INSERT_UNDO);
4284                         pasteClipboard(cur);
4285                 }
4286                 break;
4287
4288         case LFUN_FONT_EMPH:
4289         case LFUN_FONT_BOLD:
4290         case LFUN_FONT_BOLDSYMBOL:
4291         case LFUN_FONT_ROMAN:
4292         case LFUN_FONT_NOUN:
4293         case LFUN_FONT_ITAL:
4294         case LFUN_FONT_FRAK:
4295         case LFUN_FONT_TYPEWRITER:
4296         case LFUN_FONT_SANS:
4297         case LFUN_TEXTSTYLE_APPLY:
4298         case LFUN_TEXTSTYLE_UPDATE:
4299         case LFUN_FONT_SIZE:
4300         case LFUN_FONT_UNDERLINE:
4301         case LFUN_FONT_STRIKEOUT:
4302         case LFUN_FONT_UULINE:
4303         case LFUN_FONT_UWAVE:
4304         case LFUN_LANGUAGE:
4305         case LFUN_WORD_CAPITALIZE:
4306         case LFUN_WORD_UPCASE:
4307         case LFUN_WORD_LOWCASE:
4308         case LFUN_CHARS_TRANSPOSE:
4309                 if (cur.selIsMultiCell()) {
4310                         row_type rs, re;
4311                         col_type cs, ce;
4312                         getSelection(cur, rs, re, cs, ce);
4313                         Cursor tmpcur = cur;
4314                         for (row_type r = rs; r <= re; ++r) {
4315                                 for (col_type c = cs; c <= ce; ++c) {
4316                                         // cursor follows cell:
4317                                         tmpcur.idx() = tabular.cellIndex(r, c);
4318                                         // select this cell only:
4319                                         tmpcur.pit() = 0;
4320                                         tmpcur.pos() = 0;
4321                                         tmpcur.resetAnchor();
4322                                         tmpcur.pit() = tmpcur.lastpit();
4323                                         tmpcur.pos() = tmpcur.top().lastpos();
4324                                         tmpcur.setCursor(tmpcur);
4325                                         tmpcur.setSelection();
4326                                         cell(tmpcur.idx())->dispatch(tmpcur, cmd);
4327                                 }
4328                         }
4329                         break;
4330                 } else {
4331                         cell(cur.idx())->dispatch(cur, cmd);
4332                         break;
4333                 }
4334
4335         case LFUN_INSET_SETTINGS:
4336                 // relay this lfun to Inset, not to the cell.
4337                 Inset::doDispatch(cur, cmd);
4338                 break;
4339
4340         default:
4341                 // we try to handle this event in the insets dispatch function.
4342                 cell(cur.idx())->dispatch(cur, cmd);
4343                 break;
4344         }
4345 }
4346
4347
4348 // function sets an object as defined in func_status.h:
4349 // states OK, Unknown, Disabled, On, Off.
4350 bool InsetTabular::getStatus(Cursor & cur, FuncRequest const & cmd,
4351         FuncStatus & status) const
4352 {
4353         switch (cmd.action()) {
4354         case LFUN_INSET_MODIFY: {
4355                 if (&cur.inset() != this || cmd.getArg(0) != "tabular") 
4356                         break;
4357
4358                 // FIXME: We only check for the very first argument...
4359                 string const s = cmd.getArg(1);
4360                 // We always enable the lfun if it is coming from the dialog
4361                 // because the dialog makes sure all the settings are valid,
4362                 // even though the first argument might not be valid now.
4363                 if (s == "from-dialog") {
4364                         status.setEnabled(true);
4365                         return true;
4366                 }
4367
4368                 int action = Tabular::LAST_ACTION;
4369                 int i = 0;
4370                 for (; tabularFeature[i].action != Tabular::LAST_ACTION; ++i) {
4371                         if (tabularFeature[i].feature == s) {
4372                                 action = tabularFeature[i].action;
4373                                 break;
4374                         }
4375                 }
4376                 if (action == Tabular::LAST_ACTION) {
4377                         status.clear();
4378                         status.setUnknown(true);
4379                         return true;
4380                 }
4381
4382                 string const argument = cmd.getLongArg(2);
4383
4384                 row_type sel_row_start = 0;
4385                 row_type sel_row_end = 0;
4386                 col_type sel_col_start = 0;
4387                 col_type sel_col_end = 0;
4388                 Tabular::ltType dummyltt;
4389                 bool flag = true;
4390
4391                 getSelection(cur, sel_row_start, sel_row_end, sel_col_start, sel_col_end);
4392
4393                 switch (action) {
4394                 case Tabular::SET_PWIDTH:
4395                 case Tabular::SET_MPWIDTH:
4396                 case Tabular::SET_SPECIAL_COLUMN:
4397                 case Tabular::SET_SPECIAL_MULTICOLUMN:
4398                 case Tabular::APPEND_ROW:
4399                 case Tabular::APPEND_COLUMN:
4400                 case Tabular::DELETE_ROW:
4401                 case Tabular::DELETE_COLUMN:
4402                 case Tabular::COPY_ROW:
4403                 case Tabular::COPY_COLUMN:
4404                 case Tabular::SET_TOP_SPACE:
4405                 case Tabular::SET_BOTTOM_SPACE:
4406                 case Tabular::SET_INTERLINE_SPACE:
4407                         status.clear();
4408                         return true;
4409
4410                 case Tabular::SET_TABULAR_WIDTH:
4411                         status.setEnabled(!tabular.rotate &&  !tabular.is_long_tabular
4412                                 && tabular.tabular_valignment == Tabular::LYX_VALIGN_MIDDLE);
4413                         break;
4414
4415                 case Tabular::SET_DECIMAL_POINT:
4416                         status.setEnabled(
4417                                 tabular.getAlignment(cur.idx()) == LYX_ALIGN_DECIMAL);
4418                         break;
4419
4420                 case Tabular::SET_MULTICOLUMN:
4421                 case Tabular::UNSET_MULTICOLUMN:
4422                 case Tabular::MULTICOLUMN:
4423                         // If a row is set as longtable caption, it must not be allowed
4424                         // to unset that this row is a multicolumn.
4425                         status.setEnabled(sel_row_start == sel_row_end
4426                                 && !tabular.ltCaption(tabular.cellRow(cur.idx())));
4427                         status.setOnOff(tabular.isMultiColumn(cur.idx()));
4428                         break;
4429
4430                 case Tabular::SET_MULTIROW:
4431                 case Tabular::UNSET_MULTIROW:
4432                 case Tabular::MULTIROW:
4433                         // If a row is set as longtable caption, it must not be allowed
4434                         // to unset that this row is a multirow.
4435                         status.setEnabled(sel_col_start == sel_col_end
4436                                 && !tabular.ltCaption(tabular.cellRow(cur.idx())));
4437                         status.setOnOff(tabular.isMultiRow(cur.idx()));
4438                         break;
4439
4440                 case Tabular::SET_ALL_LINES:
4441                 case Tabular::UNSET_ALL_LINES:
4442                 case Tabular::SET_BORDER_LINES:
4443                         status.setEnabled(!tabular.ltCaption(tabular.cellRow(cur.idx())));
4444                         break;
4445
4446                 case Tabular::SET_LINE_TOP:
4447                 case Tabular::SET_LINE_BOTTOM:
4448                 case Tabular::SET_LINE_LEFT:
4449                 case Tabular::SET_LINE_RIGHT:
4450                         status.setEnabled(!tabular.ltCaption(tabular.cellRow(cur.idx())));
4451                         break;
4452
4453                 case Tabular::TOGGLE_LINE_TOP:
4454                         status.setEnabled(!tabular.ltCaption(tabular.cellRow(cur.idx())));
4455                         status.setOnOff(tabular.topLine(cur.idx()));
4456                         break;
4457
4458                 case Tabular::TOGGLE_LINE_BOTTOM:
4459                         status.setEnabled(!tabular.ltCaption(tabular.cellRow(cur.idx())));
4460                         status.setOnOff(tabular.bottomLine(cur.idx()));
4461                         break;
4462
4463                 case Tabular::TOGGLE_LINE_LEFT:
4464                         status.setEnabled(!tabular.ltCaption(tabular.cellRow(cur.idx())));
4465                         status.setOnOff(tabular.leftLine(cur.idx()));
4466                         break;
4467
4468                 case Tabular::TOGGLE_LINE_RIGHT:
4469                         status.setEnabled(!tabular.ltCaption(tabular.cellRow(cur.idx())));
4470                         status.setOnOff(tabular.rightLine(cur.idx()));
4471                         break;
4472
4473                 // multirow cells only inherit the alignment of the column if the column has
4474                 // no width, otherwise they are left-aligned
4475                 // therefore allow always left but right and center only if there is no width
4476                 case Tabular::M_ALIGN_LEFT:
4477                         flag = false;
4478                 case Tabular::ALIGN_LEFT:
4479                         status.setOnOff(tabular.getAlignment(cur.idx(), flag) == LYX_ALIGN_LEFT);
4480                         break;
4481
4482                 case Tabular::M_ALIGN_RIGHT:
4483                         flag = false;
4484                 case Tabular::ALIGN_RIGHT:
4485                         status.setEnabled(!(tabular.isMultiRow(cur.idx()) 
4486                                 && !tabular.getPWidth(cur.idx()).zero()));
4487                         status.setOnOff(tabular.getAlignment(cur.idx(), flag) == LYX_ALIGN_RIGHT);
4488                         break;
4489
4490                 case Tabular::M_ALIGN_CENTER:
4491                         flag = false;
4492                 case Tabular::ALIGN_CENTER:
4493                         status.setEnabled(!(tabular.isMultiRow(cur.idx()) 
4494                                 && !tabular.getPWidth(cur.idx()).zero()));
4495                         status.setOnOff(tabular.getAlignment(cur.idx(), flag) == LYX_ALIGN_CENTER);
4496                         break;
4497
4498                 case Tabular::ALIGN_BLOCK:
4499                         status.setEnabled(!tabular.getPWidth(cur.idx()).zero()
4500                                 && !tabular.isMultiRow(cur.idx()));
4501                         status.setOnOff(tabular.getAlignment(cur.idx(), flag) == LYX_ALIGN_BLOCK);
4502                         break;
4503
4504                 case Tabular::ALIGN_DECIMAL:
4505                         status.setEnabled(!tabular.isMultiRow(cur.idx()) 
4506                                 && !tabular.isMultiColumn(cur.idx()));
4507                         status.setOnOff(tabular.getAlignment(cur.idx(), true) == LYX_ALIGN_DECIMAL);
4508                         break;
4509
4510                 case Tabular::M_VALIGN_TOP:
4511                         flag = false;
4512                 case Tabular::VALIGN_TOP:
4513                         status.setEnabled(!tabular.getPWidth(cur.idx()).zero()
4514                                 && !tabular.isMultiRow(cur.idx()));
4515                         status.setOnOff(
4516                                 tabular.getVAlignment(cur.idx(), flag) == Tabular::LYX_VALIGN_TOP);
4517                         break;
4518
4519                 case Tabular::M_VALIGN_BOTTOM:
4520                         flag = false;
4521                 case Tabular::VALIGN_BOTTOM:
4522                         status.setEnabled(!tabular.getPWidth(cur.idx()).zero()
4523                                 && !tabular.isMultiRow(cur.idx()));
4524                         status.setOnOff(
4525                                 tabular.getVAlignment(cur.idx(), flag) == Tabular::LYX_VALIGN_BOTTOM);
4526                         break;
4527
4528                 case Tabular::M_VALIGN_MIDDLE:
4529                         flag = false;
4530                 case Tabular::VALIGN_MIDDLE:
4531                         status.setEnabled(!tabular.getPWidth(cur.idx()).zero()
4532                                 && !tabular.isMultiRow(cur.idx()));
4533                         status.setOnOff(
4534                                 tabular.getVAlignment(cur.idx(), flag) == Tabular::LYX_VALIGN_MIDDLE);
4535                         break;
4536
4537                 case Tabular::SET_LONGTABULAR:
4538                         // setting as longtable is not allowed when table is inside a float
4539                         if (cur.innerInsetOfType(FLOAT_CODE) != 0
4540                                 || cur.innerInsetOfType(WRAP_CODE) != 0)
4541                                 status.setEnabled(false);
4542                         else
4543                                 status.setEnabled(true);
4544                         status.setOnOff(tabular.is_long_tabular);
4545                         break;
4546
4547                 case Tabular::UNSET_LONGTABULAR:
4548                         status.setOnOff(!tabular.is_long_tabular);
4549                         break;
4550
4551                 case Tabular::TOGGLE_ROTATE_TABULAR:
4552                 case Tabular::SET_ROTATE_TABULAR:
4553                         status.setEnabled(tabular.tabular_width.zero());
4554                         status.setOnOff(tabular.rotate);
4555                         break;
4556
4557                 case Tabular::TABULAR_VALIGN_TOP:
4558                         status.setEnabled(tabular.tabular_width.zero());
4559                         status.setOnOff(tabular.tabular_valignment 
4560                                 == Tabular::LYX_VALIGN_TOP);
4561                         break;
4562                 case Tabular::TABULAR_VALIGN_MIDDLE:
4563                         status.setEnabled(tabular.tabular_width.zero());
4564                         status.setOnOff(tabular.tabular_valignment 
4565                                 == Tabular::LYX_VALIGN_MIDDLE);
4566                         break;
4567                 case Tabular::TABULAR_VALIGN_BOTTOM:
4568                         status.setEnabled(tabular.tabular_width.zero());
4569                         status.setOnOff(tabular.tabular_valignment 
4570                                 == Tabular::LYX_VALIGN_BOTTOM);
4571                         break;
4572
4573                 case Tabular::LONGTABULAR_ALIGN_LEFT:
4574                         status.setOnOff(tabular.longtabular_alignment 
4575                                 == Tabular::LYX_LONGTABULAR_ALIGN_LEFT);
4576                         break;
4577                 case Tabular::LONGTABULAR_ALIGN_CENTER:
4578                         status.setOnOff(tabular.longtabular_alignment 
4579                                 == Tabular::LYX_LONGTABULAR_ALIGN_CENTER);
4580                         break;
4581                 case Tabular::LONGTABULAR_ALIGN_RIGHT:
4582                         status.setOnOff(tabular.longtabular_alignment 
4583                                 == Tabular::LYX_LONGTABULAR_ALIGN_RIGHT);
4584                         break;
4585
4586                 case Tabular::UNSET_ROTATE_TABULAR:
4587                         status.setOnOff(!tabular.rotate);
4588                         break;
4589
4590                 case Tabular::TOGGLE_ROTATE_CELL:
4591                 case Tabular::SET_ROTATE_CELL:
4592                         status.setOnOff(!oneCellHasRotationState(false,
4593                                 sel_row_start, sel_row_end, sel_col_start, sel_col_end));
4594                         break;
4595
4596                 case Tabular::UNSET_ROTATE_CELL:
4597                         status.setOnOff(!oneCellHasRotationState(true,
4598                                 sel_row_start, sel_row_end, sel_col_start, sel_col_end));
4599                         break;
4600
4601                 case Tabular::SET_USEBOX:
4602                         status.setOnOff(convert<int>(argument) == tabular.getUsebox(cur.idx()));
4603                         break;
4604
4605                 // every row can only be one thing:
4606                 // either a footer or header
4607                 case Tabular::SET_LTFIRSTHEAD:
4608                         status.setEnabled(sel_row_start == sel_row_end);
4609                         status.setOnOff(tabular.getRowOfLTFirstHead(sel_row_start, dummyltt));
4610                         break;
4611
4612                 case Tabular::UNSET_LTFIRSTHEAD:
4613                         status.setOnOff(!tabular.getRowOfLTFirstHead(sel_row_start, dummyltt));
4614                         break;
4615
4616                 case Tabular::SET_LTHEAD:
4617                         status.setEnabled(sel_row_start == sel_row_end);
4618                         status.setOnOff(tabular.getRowOfLTHead(sel_row_start, dummyltt));
4619                         break;
4620
4621                 case Tabular::UNSET_LTHEAD:
4622                         status.setOnOff(!tabular.getRowOfLTHead(sel_row_start, dummyltt));
4623                         break;
4624
4625                 case Tabular::SET_LTFOOT:
4626                         status.setEnabled(sel_row_start == sel_row_end);
4627                         status.setOnOff(tabular.getRowOfLTFoot(sel_row_start, dummyltt));
4628                         break;
4629
4630                 case Tabular::UNSET_LTFOOT:
4631                         status.setOnOff(!tabular.getRowOfLTFoot(sel_row_start, dummyltt));
4632                         break;
4633
4634                 case Tabular::SET_LTLASTFOOT:
4635                         status.setEnabled(sel_row_start == sel_row_end);
4636                         status.setOnOff(tabular.getRowOfLTLastFoot(sel_row_start, dummyltt));
4637                         break;
4638
4639                 case Tabular::UNSET_LTLASTFOOT:
4640                         status.setOnOff(!tabular.getRowOfLTLastFoot(sel_row_start, dummyltt));
4641                         break;
4642
4643                 case Tabular::SET_LTNEWPAGE:
4644                         status.setOnOff(tabular.getLTNewPage(sel_row_start));
4645                         break;
4646
4647                 // only one row in head/firsthead/foot/lasthead can be the caption
4648                 // and a multirow cannot be set as caption
4649                 case Tabular::SET_LTCAPTION:
4650                         status.setEnabled(sel_row_start == sel_row_end
4651                                 && (!tabular.getRowOfLTFirstHead(sel_row_start, dummyltt)
4652                                  || !tabular.haveLTCaption(Tabular::CAPTION_FIRSTHEAD))
4653                                 && (!tabular.getRowOfLTHead(sel_row_start, dummyltt)
4654                                  || !tabular.haveLTCaption(Tabular::CAPTION_HEAD))
4655                                 && (!tabular.getRowOfLTFoot(sel_row_start, dummyltt)
4656                                  || !tabular.haveLTCaption(Tabular::CAPTION_FOOT))
4657                                 && (!tabular.getRowOfLTLastFoot(sel_row_start, dummyltt)
4658                                  || !tabular.haveLTCaption(Tabular::CAPTION_LASTFOOT))
4659                                 && !tabular.isMultiRow(sel_row_start));
4660                         status.setOnOff(tabular.ltCaption(sel_row_start));
4661                         break;
4662
4663                 case Tabular::UNSET_LTCAPTION:
4664                         status.setEnabled(sel_row_start == sel_row_end && tabular.ltCaption(sel_row_start));
4665                         break;
4666
4667                 case Tabular::TOGGLE_LTCAPTION:
4668                         status.setEnabled(sel_row_start == sel_row_end && (tabular.ltCaption(sel_row_start)
4669                                 || ((!tabular.getRowOfLTFirstHead(sel_row_start, dummyltt)
4670                                   || !tabular.haveLTCaption(Tabular::CAPTION_FIRSTHEAD))
4671                                  && (!tabular.getRowOfLTHead(sel_row_start, dummyltt)
4672                                   || !tabular.haveLTCaption(Tabular::CAPTION_HEAD))
4673                                  && (!tabular.getRowOfLTFoot(sel_row_start, dummyltt)
4674                                   || !tabular.haveLTCaption(Tabular::CAPTION_FOOT))
4675                                  && (!tabular.getRowOfLTLastFoot(sel_row_start, dummyltt)
4676                                   || !tabular.haveLTCaption(Tabular::CAPTION_LASTFOOT)))));
4677                         status.setOnOff(tabular.ltCaption(sel_row_start));
4678                         break;
4679
4680                 case Tabular::SET_BOOKTABS:
4681                         status.setOnOff(tabular.use_booktabs);
4682                         break;
4683
4684                 case Tabular::UNSET_BOOKTABS:
4685                         status.setOnOff(!tabular.use_booktabs);
4686                         break;
4687
4688                 default:
4689                         status.clear();
4690                         status.setEnabled(false);
4691                         break;
4692                 }
4693                 return true;
4694         }
4695
4696         // These are only enabled inside tabular
4697         case LFUN_CELL_BACKWARD:
4698         case LFUN_CELL_FORWARD:
4699                 status.setEnabled(true);
4700                 return true;
4701
4702         // disable these with multiple cells selected
4703         case LFUN_INSET_INSERT:
4704         case LFUN_TABULAR_INSERT:
4705         case LFUN_FLEX_INSERT:
4706         case LFUN_FLOAT_INSERT:
4707         case LFUN_FLOAT_WIDE_INSERT:
4708         case LFUN_FOOTNOTE_INSERT:
4709         case LFUN_MARGINALNOTE_INSERT:
4710         case LFUN_MATH_INSERT:
4711         case LFUN_MATH_MODE:
4712         case LFUN_MATH_MUTATE:
4713         case LFUN_MATH_DISPLAY:
4714         case LFUN_NOTE_INSERT:
4715         case LFUN_ARGUMENT_INSERT:
4716         case LFUN_BOX_INSERT:
4717         case LFUN_BRANCH_INSERT:
4718         case LFUN_PHANTOM_INSERT:
4719         case LFUN_WRAP_INSERT:
4720         case LFUN_PREVIEW_INSERT:
4721         case LFUN_ERT_INSERT: {
4722                 if (cur.selIsMultiCell()) {
4723                         status.setEnabled(false);
4724                         return true;
4725                 } else
4726                         return cell(cur.idx())->getStatus(cur, cmd, status);
4727         }
4728
4729         // disable in non-fixed-width cells
4730         case LFUN_BREAK_PARAGRAPH:
4731                 // multirow does not allow paragraph breaks
4732                 if (tabular.isMultiRow(cur.idx())) {
4733                         status.setEnabled(false);
4734                         return true;
4735                 }
4736         case LFUN_NEWLINE_INSERT: {
4737                 if (tabular.getPWidth(cur.idx()).zero()) {
4738                         status.setEnabled(false);
4739                         return true;
4740                 } else
4741                         return cell(cur.idx())->getStatus(cur, cmd, status);
4742         }
4743
4744         case LFUN_NEWPAGE_INSERT:
4745                 status.setEnabled(false);
4746                 return true;
4747
4748         case LFUN_PASTE:
4749                 if (tabularStackDirty() && theClipboard().isInternal()) {
4750                         if (cur.selIsMultiCell()) {
4751                                 row_type rs, re;
4752                                 col_type cs, ce;
4753                                 getSelection(cur, rs, re, cs, ce);
4754                                 if (paste_tabular && paste_tabular->ncols() == ce - cs + 1
4755                                           && paste_tabular->nrows() == re - rs + 1)
4756                                         status.setEnabled(true);        
4757                                 else {
4758                                         status.setEnabled(false);
4759                                         status.message(_("Selection size should match clipboard content."));
4760                                 }
4761                         } else
4762                                 status.setEnabled(true);
4763                         return true;
4764                 }
4765                 return cell(cur.idx())->getStatus(cur, cmd, status);
4766
4767         case LFUN_INSET_SETTINGS:
4768                 // relay this lfun to Inset, not to the cell.
4769                 return Inset::getStatus(cur, cmd, status);
4770
4771         default:
4772                 // we try to handle this event in the insets dispatch function.
4773                 return cell(cur.idx())->getStatus(cur, cmd, status);
4774         }
4775         return false;
4776 }
4777
4778
4779 Inset::DisplayType InsetTabular::display() const
4780 {
4781                 if (tabular.is_long_tabular) {
4782                         switch (tabular.longtabular_alignment) {
4783                         case Tabular::LYX_LONGTABULAR_ALIGN_LEFT:
4784                                 return AlignLeft;
4785                         case Tabular::LYX_LONGTABULAR_ALIGN_CENTER:
4786                                 return AlignCenter;
4787                         case Tabular::LYX_LONGTABULAR_ALIGN_RIGHT:
4788                                 return AlignRight;
4789                         default:
4790                                 return AlignCenter;
4791                         }
4792                 } else
4793                         return Inline;
4794 }
4795
4796
4797 void InsetTabular::latex(otexstream & os, OutputParams const & runparams) const
4798 {
4799         tabular.latex(os, runparams);
4800 }
4801
4802
4803 int InsetTabular::plaintext(odocstream & os, OutputParams const & runparams) const
4804 {
4805         os << '\n'; // output table on a new line
4806         int const dp = runparams.linelen > 0 ? runparams.depth : 0;
4807         tabular.plaintext(os, runparams, dp, false, 0);
4808         return PLAINTEXT_NEWLINE;
4809 }
4810
4811
4812 int InsetTabular::docbook(odocstream & os, OutputParams const & runparams) const
4813 {
4814         int ret = 0;
4815         Inset * master = 0;
4816
4817         // FIXME: Why not pass a proper DocIterator here?
4818 #if 0
4819         // if the table is inside a float it doesn't need the informaltable
4820         // wrapper. Search for it.
4821         for (master = owner(); master; master = master->owner())
4822                 if (master->lyxCode() == FLOAT_CODE)
4823                         break;
4824 #endif
4825
4826         if (!master) {
4827                 os << "<informaltable>";
4828                 ++ret;
4829         }
4830         ret += tabular.docbook(os, runparams);
4831         if (!master) {
4832                 os << "</informaltable>";
4833                 ++ret;
4834         }
4835         return ret;
4836 }
4837
4838
4839 docstring InsetTabular::xhtml(XHTMLStream & xs, OutputParams const & rp) const
4840 {
4841         return tabular.xhtml(xs, rp);
4842 }
4843
4844
4845 void InsetTabular::validate(LaTeXFeatures & features) const
4846 {
4847         tabular.validate(features);
4848         // FIXME XHTML
4849         // It'd be better to be able to get this from an InsetLayout, but at present
4850         // InsetLayouts do not seem really to work for things that aren't InsetTexts.
4851         if (features.runparams().flavor == OutputParams::HTML)
4852                 features.addCSSSnippet(
4853                         "table { border: 1px solid black; display: inline-block; }\n"
4854                         "td { border: 1px solid black; padding: 0.5ex; }");
4855 }
4856
4857
4858 shared_ptr<InsetTableCell const> InsetTabular::cell(idx_type idx) const
4859 {
4860         return tabular.cellInset(idx);
4861 }
4862
4863
4864 shared_ptr<InsetTableCell> InsetTabular::cell(idx_type idx)
4865 {
4866         return tabular.cellInset(idx);
4867 }
4868
4869
4870 void InsetTabular::cursorPos(BufferView const & bv,
4871                 CursorSlice const & sl, bool boundary, int & x, int & y) const
4872 {
4873         cell(sl.idx())->cursorPos(bv, sl, boundary, x, y);
4874
4875         // y offset     correction
4876         y += cellYPos(sl.idx());
4877         y += tabular.textVOffset(sl.idx());
4878         y += offset_valign_;
4879
4880         // x offset correction
4881         x += cellXPos(sl.idx());
4882         x += tabular.textHOffset(sl.idx());
4883         x += ADD_TO_TABULAR_WIDTH;
4884         x += scx_;
4885 }
4886
4887
4888 int InsetTabular::dist(BufferView & bv, idx_type const cell, int x, int y) const
4889 {
4890         int xx = 0;
4891         int yy = 0;
4892         Inset const & inset = *tabular.cellInset(cell);
4893         Point o = bv.coordCache().getInsets().xy(&inset);
4894         int const xbeg = o.x_ - tabular.textHOffset(cell);
4895         int const xend = xbeg + tabular.cellWidth(cell);
4896         row_type const row = tabular.cellRow(cell);
4897         int const ybeg = o.y_ - tabular.rowAscent(row)
4898                 - tabular.interRowSpace(row);
4899         int const yend = ybeg + tabular.cellHeight(cell);
4900
4901         if (x < xbeg)
4902                 xx = xbeg - x;
4903         else if (x > xend)
4904                 xx = x - xend;
4905
4906         if (y < ybeg)
4907                 yy = ybeg - y;
4908         else if (y > yend)
4909                 yy = y - yend;
4910
4911         //lyxerr << " xbeg=" << xbeg << "  xend=" << xend
4912         //       << " ybeg=" << ybeg << " yend=" << yend
4913         //       << " xx=" << xx << " yy=" << yy
4914         //       << " dist=" << xx + yy << endl;
4915         return xx + yy;
4916 }
4917
4918
4919 Inset * InsetTabular::editXY(Cursor & cur, int x, int y)
4920 {
4921         //lyxerr << "InsetTabular::editXY: " << this << endl;
4922         cur.setSelection(false);
4923         cur.push(*this);
4924         cur.idx() = getNearestCell(cur.bv(), x, y);
4925         resetPos(cur);
4926         return cur.bv().textMetrics(&cell(cur.idx())->text()).editXY(cur, x, y);
4927 }
4928
4929
4930 void InsetTabular::setCursorFromCoordinates(Cursor & cur, int x, int y) const
4931 {
4932         cur.idx() = getNearestCell(cur.bv(), x, y);
4933         cur.bv().textMetrics(&cell(cur.idx())->text()).setCursorFromCoordinates(cur, x, y);
4934 }
4935
4936
4937 InsetTabular::idx_type InsetTabular::getNearestCell(BufferView & bv, int x, int y) const
4938 {
4939         idx_type idx_min = 0;
4940         int dist_min = numeric_limits<int>::max();
4941         for (idx_type i = 0, n = nargs(); i != n; ++i) {
4942                 if (bv.coordCache().getInsets().has(tabular.cellInset(i).get())) {
4943                         int const d = dist(bv, i, x, y);
4944                         if (d < dist_min) {
4945                                 dist_min = d;
4946                                 idx_min = i;
4947                         }
4948                 }
4949         }
4950         return idx_min;
4951 }
4952
4953
4954 int InsetTabular::cellYPos(idx_type const cell) const
4955 {
4956         row_type row = tabular.cellRow(cell);
4957         int ly = 0;
4958         for (row_type r = 0; r < row; ++r)
4959                 ly += tabular.rowDescent(r) + tabular.rowAscent(r + 1) 
4960                         + tabular.interRowSpace(r + 1);
4961         return ly;
4962 }
4963
4964
4965 int InsetTabular::cellXPos(idx_type const cell) const
4966 {
4967         col_type col = tabular.cellColumn(cell);
4968         int lx = 0;
4969         for (col_type c = 0; c < col; ++c)
4970                 lx += tabular.column_info[c].width;
4971         return lx;
4972 }
4973
4974
4975 void InsetTabular::resetPos(Cursor & cur) const
4976 {
4977         BufferView & bv = cur.bv();
4978         int const maxwidth = bv.workWidth();
4979
4980         int const scx_old = scx_;
4981         int const i = cur.find(this);
4982         if (i == -1) {
4983                 scx_ = 0;
4984         } else {
4985                 int const X1 = 0;
4986                 int const X2 = maxwidth;
4987                 int const offset = ADD_TO_TABULAR_WIDTH + 2;
4988                 int const x1 = xo(cur.bv()) + cellXPos(cur[i].idx()) + offset;
4989                 int const x2 = x1 + tabular.cellWidth(cur[i].idx());
4990
4991                 if (x1 < X1)
4992                         scx_ = X1 + 20 - x1;
4993                 else if (x2 > X2)
4994                         scx_ = X2 - 20 - x2;
4995                 else
4996                         scx_ = 0;
4997         }
4998
4999         // only update if offset changed
5000         if (scx_ != scx_old)
5001                 cur.screenUpdateFlags(Update::Force | Update::FitCursor);
5002 }
5003
5004
5005 void InsetTabular::moveNextCell(Cursor & cur, EntryDirection entry_from)
5006 {
5007         row_type const row = tabular.cellRow(cur.idx());
5008         col_type const col = tabular.cellColumn(cur.idx());
5009
5010         if (isRightToLeft(cur)) {
5011                 if (tabular.cellColumn(cur.idx()) == 0) {
5012                         if (row == tabular.nrows() - 1)
5013                                 return;
5014                         cur.idx() = tabular.cellBelow(tabular.getLastCellInRow(row));
5015                 } else {
5016                         if (cur.idx() == 0)
5017                                 return;
5018                         if (col == 0)
5019                                 cur.idx() = tabular.getLastCellInRow(row - 1);
5020                         else
5021                                 cur.idx() = tabular.cellIndex(row, col - 1);
5022                 }
5023         } else {
5024                 if (tabular.isLastCell(cur.idx()))
5025                         return;
5026                 if (cur.idx() == tabular.getLastCellInRow(row))
5027                         cur.idx() = tabular.cellIndex(row + 1, 0);
5028                 else {
5029                         col_type const colnextcell = col + tabular.columnSpan(cur.idx());
5030                         cur.idx() = tabular.cellIndex(row, colnextcell);
5031                 }
5032         }
5033
5034         cur.boundary(false);
5035
5036         if (cur.selIsMultiCell()) {
5037                 cur.pit() = cur.lastpit();
5038                 cur.pos() = cur.lastpos();
5039                 resetPos(cur);
5040                 return;
5041         }
5042
5043         cur.pit() = 0;
5044         cur.pos() = 0;
5045
5046         // in visual mode, place cursor at extreme left or right
5047         
5048         switch(entry_from) {
5049
5050         case ENTRY_DIRECTION_RIGHT:
5051                 cur.posVisToRowExtremity(false /* !left */);
5052                 break;
5053         case ENTRY_DIRECTION_LEFT:
5054                 cur.posVisToRowExtremity(true /* left */);
5055                 break;
5056         case ENTRY_DIRECTION_IGNORE:
5057                 // nothing to do in this case
5058                 break;
5059
5060         }
5061         cur.setCurrentFont();
5062         resetPos(cur);
5063 }
5064
5065
5066 void InsetTabular::movePrevCell(Cursor & cur, EntryDirection entry_from)
5067 {
5068         row_type const row = tabular.cellRow(cur.idx());
5069         col_type const col = tabular.cellColumn(cur.idx());
5070
5071         if (isRightToLeft(cur)) {
5072                 if (cur.idx() == tabular.getLastCellInRow(row)) {
5073                         if (row == 0)
5074                                 return;
5075                         cur.idx() = tabular.getFirstCellInRow(row);
5076                         cur.idx() = tabular.cellAbove(cur.idx());
5077                 } else {
5078                         if (tabular.isLastCell(cur.idx()))
5079                                 return;
5080                         if (cur.idx() == tabular.getLastCellInRow(row))
5081                                 cur.idx() = tabular.cellIndex(row + 1, 0);
5082                         else
5083                                 cur.idx() = tabular.cellIndex(row, col + 1);
5084                 }
5085         } else {
5086                 if (cur.idx() == 0) // first cell
5087                         return;
5088                 if (col == 0)
5089                         cur.idx() = tabular.getLastCellInRow(row - 1);
5090                 else
5091                         cur.idx() = tabular.cellIndex(row, col - 1);
5092         }
5093
5094         if (cur.selIsMultiCell()) {
5095                 cur.pit() = cur.lastpit();
5096                 cur.pos() = cur.lastpos();
5097                 resetPos(cur);
5098                 return;
5099         }
5100
5101         cur.pit() = cur.lastpit();
5102         cur.pos() = cur.lastpos();
5103
5104         // in visual mode, place cursor at extreme left or right
5105         
5106         switch(entry_from) {
5107
5108         case ENTRY_DIRECTION_RIGHT:
5109                 cur.posVisToRowExtremity(false /* !left */);
5110                 break;
5111         case ENTRY_DIRECTION_LEFT:
5112                 cur.posVisToRowExtremity(true /* left */);
5113                 break;
5114         case ENTRY_DIRECTION_IGNORE:
5115                 // nothing to do in this case
5116                 break;
5117
5118         }
5119         cur.setCurrentFont();
5120         resetPos(cur);
5121 }
5122
5123
5124 bool InsetTabular::tabularFeatures(Cursor & cur, string const & argument)
5125 {
5126         istringstream is(argument);
5127         string s;
5128         is >> s;
5129         if (insetCode(s) != TABULAR_CODE)
5130                 return false;
5131
5132         // Safe guard.
5133         size_t safe_guard = 0;
5134         for (;;) {
5135                 if (is.eof())
5136                         break;
5137                 safe_guard++;
5138                 if (safe_guard > 1000) {
5139                         LYXERR0("parameter max count reached!");
5140                         break;
5141                 }
5142                 is >> s;
5143                 Tabular::Feature action = Tabular::LAST_ACTION;
5144
5145                 size_t i = 0;
5146                 for (; tabularFeature[i].action != Tabular::LAST_ACTION; ++i) {
5147                         if (s != tabularFeature[i].feature)
5148                                 continue;
5149
5150                         action = tabularFeature[i].action;
5151                         break;
5152                 }
5153                 if (action == Tabular::LAST_ACTION) {
5154                         LYXERR0("Feature not found " << s);
5155                         continue;
5156                 }
5157                 string val;
5158                 if (tabularFeature[i].need_value)
5159                         is >> val;
5160                 LYXERR(Debug::DEBUG, "Feature: " << s << "\t\tvalue: " << val);
5161                 tabularFeatures(cur, action, val);
5162         }
5163         return true;
5164 }
5165
5166
5167 static void checkLongtableSpecial(Tabular::ltType & ltt,
5168                           string const & special, bool & flag)
5169 {
5170         if (special == "dl_above") {
5171                 ltt.topDL = flag;
5172                 ltt.set = false;
5173         } else if (special == "dl_below") {
5174                 ltt.bottomDL = flag;
5175                 ltt.set = false;
5176         } else if (special == "empty") {
5177                 ltt.empty = flag;
5178                 ltt.set = false;
5179         } else if (flag) {
5180                 ltt.empty = false;
5181                 ltt.set = true;
5182         }
5183 }
5184
5185
5186 bool InsetTabular::oneCellHasRotationState(bool rotated,
5187                 row_type row_start, row_type row_end,
5188                 col_type col_start, col_type col_end) const 
5189 {
5190         for (row_type r = row_start; r <= row_end; ++r)
5191                 for (col_type c = col_start; c <= col_end; ++c)
5192                         if (tabular.getRotateCell(tabular.cellIndex(r, c)) == rotated)
5193                                 return true;
5194
5195         return false;
5196 }
5197
5198 void InsetTabular::tabularFeatures(Cursor & cur,
5199         Tabular::Feature feature, string const & value)
5200 {
5201         col_type sel_col_start;
5202         col_type sel_col_end;
5203         row_type sel_row_start;
5204         row_type sel_row_end;
5205         bool setLines = false;
5206         LyXAlignment setAlign = LYX_ALIGN_LEFT;
5207         Tabular::VAlignment setVAlign = Tabular::LYX_VALIGN_TOP;
5208
5209         switch (feature) {
5210
5211         case Tabular::M_ALIGN_LEFT:
5212         case Tabular::ALIGN_LEFT:
5213                 setAlign = LYX_ALIGN_LEFT;
5214                 break;
5215
5216         case Tabular::M_ALIGN_RIGHT:
5217         case Tabular::ALIGN_RIGHT:
5218                 setAlign = LYX_ALIGN_RIGHT;
5219                 break;
5220
5221         case Tabular::M_ALIGN_CENTER:
5222         case Tabular::ALIGN_CENTER:
5223                 setAlign = LYX_ALIGN_CENTER;
5224                 break;
5225
5226         case Tabular::ALIGN_BLOCK:
5227                 setAlign = LYX_ALIGN_BLOCK;
5228                 break;
5229
5230         case Tabular::ALIGN_DECIMAL:
5231                 setAlign = LYX_ALIGN_DECIMAL;
5232                 break;
5233
5234         case Tabular::M_VALIGN_TOP:
5235         case Tabular::VALIGN_TOP:
5236                 setVAlign = Tabular::LYX_VALIGN_TOP;
5237                 break;
5238
5239         case Tabular::M_VALIGN_BOTTOM:
5240         case Tabular::VALIGN_BOTTOM:
5241                 setVAlign = Tabular::LYX_VALIGN_BOTTOM;
5242                 break;
5243
5244         case Tabular::M_VALIGN_MIDDLE:
5245         case Tabular::VALIGN_MIDDLE:
5246                 setVAlign = Tabular::LYX_VALIGN_MIDDLE;
5247                 break;
5248
5249         default:
5250                 break;
5251         }
5252
5253         cur.recordUndoInset(ATOMIC_UNDO, this);
5254
5255         getSelection(cur, sel_row_start, sel_row_end, sel_col_start, sel_col_end);
5256         row_type const row = tabular.cellRow(cur.idx());
5257         col_type const column = tabular.cellColumn(cur.idx());
5258         bool flag = true;
5259         Tabular::ltType ltt;
5260
5261         switch (feature) {
5262
5263         case Tabular::SET_TABULAR_WIDTH:
5264                 tabular.setTabularWidth(Length(value));
5265                 break;
5266
5267         case Tabular::SET_PWIDTH: {
5268                 Length const len(value);
5269                 tabular.setColumnPWidth(cur, cur.idx(), len);
5270                 if (len.zero()
5271                     && tabular.getAlignment(cur.idx(), true) == LYX_ALIGN_BLOCK)
5272                         tabularFeatures(cur, Tabular::ALIGN_CENTER, string());
5273                 break;
5274         }
5275
5276         case Tabular::SET_MPWIDTH:
5277                 tabular.setMColumnPWidth(cur, cur.idx(), Length(value));
5278                 break;
5279
5280         case Tabular::SET_MROFFSET:
5281                 tabular.setMROffset(cur, cur.idx(), Length(value));
5282                 break;
5283
5284         case Tabular::SET_SPECIAL_COLUMN:
5285         case Tabular::SET_SPECIAL_MULTICOLUMN:
5286                 if (value == "none")
5287                         tabular.setAlignSpecial(cur.idx(), docstring(), feature);
5288                 else
5289                         tabular.setAlignSpecial(cur.idx(), from_utf8(value), feature);
5290                 break;
5291
5292         case Tabular::APPEND_ROW:
5293                 // append the row into the tabular
5294                 tabular.appendRow(cur.idx());
5295                 break;
5296
5297         case Tabular::APPEND_COLUMN:
5298                 // append the column into the tabular
5299                 tabular.appendColumn(cur.idx());
5300                 cur.idx() = tabular.cellIndex(row, column);
5301                 break;
5302
5303         case Tabular::DELETE_ROW:
5304                 for (row_type r = sel_row_start; r <= sel_row_end; ++r)
5305                         tabular.deleteRow(sel_row_start);
5306                 if (sel_row_start >= tabular.nrows())
5307                         --sel_row_start;
5308                 cur.idx() = tabular.cellIndex(sel_row_start, column);
5309                 cur.pit() = 0;
5310                 cur.pos() = 0;
5311                 cur.setSelection(false);
5312                 break;
5313
5314         case Tabular::DELETE_COLUMN:
5315                 for (col_type c = sel_col_start; c <= sel_col_end; ++c)
5316                         tabular.deleteColumn(sel_col_start);
5317                 if (sel_col_start >= tabular.ncols())
5318                         --sel_col_start;
5319                 cur.idx() = tabular.cellIndex(row, sel_col_start);
5320                 cur.pit() = 0;
5321                 cur.pos() = 0;
5322                 cur.setSelection(false);
5323                 break;
5324
5325         case Tabular::COPY_ROW:
5326                 tabular.copyRow(row);
5327                 break;
5328
5329         case Tabular::COPY_COLUMN:
5330                 tabular.copyColumn(column);
5331                 cur.idx() = tabular.cellIndex(row, column);
5332                 break;
5333
5334         case Tabular::SET_LINE_TOP:
5335         case Tabular::TOGGLE_LINE_TOP: {
5336                 bool lineSet = (feature == Tabular::SET_LINE_TOP)
5337                                ? (value == "true") : !tabular.topLine(cur.idx());
5338                 for (row_type r = sel_row_start; r <= sel_row_end; ++r)
5339                         for (col_type c = sel_col_start; c <= sel_col_end; ++c)
5340                                 tabular.setTopLine(tabular.cellIndex(r, c), lineSet);
5341                 break;
5342         }
5343
5344         case Tabular::SET_LINE_BOTTOM:
5345         case Tabular::TOGGLE_LINE_BOTTOM: {
5346                 bool lineSet = (feature == Tabular::SET_LINE_BOTTOM)
5347                                ? (value == "true") : !tabular.bottomLine(cur.idx());
5348                 for (row_type r = sel_row_start; r <= sel_row_end; ++r)
5349                         for (col_type c = sel_col_start; c <= sel_col_end; ++c)
5350                                 tabular.setBottomLine(tabular.cellIndex(r, c), lineSet);
5351                 break;
5352         }
5353
5354         case Tabular::SET_LINE_LEFT:
5355         case Tabular::TOGGLE_LINE_LEFT: {
5356                 bool lineSet = (feature == Tabular::SET_LINE_LEFT)
5357                                ? (value == "true") : !tabular.leftLine(cur.idx());
5358                 for (row_type r = sel_row_start; r <= sel_row_end; ++r)
5359                         for (col_type c = sel_col_start; c <= sel_col_end; ++c)
5360                                 tabular.setLeftLine(tabular.cellIndex(r, c), lineSet);
5361                 break;
5362         }
5363
5364         case Tabular::SET_LINE_RIGHT:
5365         case Tabular::TOGGLE_LINE_RIGHT: {
5366                 bool lineSet = (feature == Tabular::SET_LINE_RIGHT)
5367                                ? (value == "true") : !tabular.rightLine(cur.idx());
5368                 for (row_type r = sel_row_start; r <= sel_row_end; ++r)
5369                         for (col_type c = sel_col_start; c <= sel_col_end; ++c)
5370                                 tabular.setRightLine(tabular.cellIndex(r, c), lineSet);
5371                 break;
5372         }
5373
5374         case Tabular::M_ALIGN_LEFT:
5375         case Tabular::M_ALIGN_RIGHT:
5376         case Tabular::M_ALIGN_CENTER:
5377         case Tabular::ALIGN_LEFT:
5378         case Tabular::ALIGN_RIGHT:
5379         case Tabular::ALIGN_CENTER:
5380         case Tabular::ALIGN_BLOCK:
5381         case Tabular::ALIGN_DECIMAL:
5382                 for (row_type r = sel_row_start; r <= sel_row_end; ++r)
5383                         for (col_type c = sel_col_start; c <= sel_col_end; ++c)
5384                                 tabular.setAlignment(tabular.cellIndex(r, c), setAlign,
5385                                 !tabular.getPWidth(c).zero());
5386                 break;
5387
5388         case Tabular::M_VALIGN_TOP:
5389         case Tabular::M_VALIGN_BOTTOM:
5390         case Tabular::M_VALIGN_MIDDLE:
5391                 flag = false;
5392         case Tabular::VALIGN_TOP:
5393         case Tabular::VALIGN_BOTTOM:
5394         case Tabular::VALIGN_MIDDLE:
5395                 for (row_type r = sel_row_start; r <= sel_row_end; ++r)
5396                         for (col_type c = sel_col_start; c <= sel_col_end; ++c)
5397                                 tabular.setVAlignment(tabular.cellIndex(r, c), setVAlign, flag);
5398                 break;
5399
5400         case Tabular::SET_MULTICOLUMN: {
5401                 if (!cur.selection()) {
5402                         // just multicol for one single cell
5403                         // check whether we are completely in a multicol
5404                         if (!tabular.isMultiColumn(cur.idx()))
5405                                 tabular.setMultiColumn(cur.idx(), 1,
5406                                         tabular.rightLine(cur.idx()));
5407                         break;
5408                 }
5409                 // we have a selection so this means we just add all this
5410                 // cells to form a multicolumn cell
5411                 idx_type const s_start = cur.selBegin().idx();
5412                 row_type const col_start = tabular.cellColumn(s_start);
5413                 row_type const col_end = tabular.cellColumn(cur.selEnd().idx());
5414                 cur.idx() = tabular.setMultiColumn(s_start, col_end - col_start + 1,
5415                                                    tabular.rightLine(cur.selEnd().idx()));
5416                 cur.pit() = 0;
5417                 cur.pos() = 0;
5418                 cur.setSelection(false);
5419                 break;
5420         }
5421
5422         case Tabular::UNSET_MULTICOLUMN: {
5423                 if (!cur.selection()) {
5424                         if (tabular.isMultiColumn(cur.idx()))
5425                                 tabular.unsetMultiColumn(cur.idx());
5426                 }
5427                 break;
5428         }
5429
5430         case Tabular::MULTICOLUMN: {
5431                 if (!cur.selection()) {
5432                         if (tabular.isMultiColumn(cur.idx()))
5433                                 tabularFeatures(cur, Tabular::UNSET_MULTICOLUMN);
5434                         else
5435                                 tabularFeatures(cur, Tabular::SET_MULTICOLUMN);
5436                         break;
5437                 }
5438                 bool merge = false;
5439                 for (col_type c = sel_col_start; c <= sel_col_end; ++c) {
5440                         row_type const r = sel_row_start;
5441                         if (!tabular.isMultiColumn(tabular.cellIndex(r, c))
5442                             || (r > sel_row_start && !tabular.isPartOfMultiColumn(r, c)))
5443                                 merge = true;
5444                 }
5445                 // If the selection contains at least one singlecol cell
5446                 // or multiple multicol cells,
5447                 // we assume the user will merge is to a single multicol
5448                 if (merge)
5449                         tabularFeatures(cur, Tabular::SET_MULTICOLUMN);
5450                 else
5451                         tabularFeatures(cur, Tabular::UNSET_MULTICOLUMN);
5452                 break;
5453         }
5454
5455         case Tabular::SET_MULTIROW: {
5456                 if (!cur.selection()) {
5457                         // just multirow for one single cell
5458                         // check whether we are completely in a multirow
5459                         if (!tabular.isMultiRow(cur.idx()))
5460                                 tabular.setMultiRow(cur.idx(), 1,
5461                                                     tabular.bottomLine(cur.idx()));
5462                         break;
5463                 }
5464                 // we have a selection so this means we just add all this
5465                 // cells to form a multirow cell
5466                 idx_type const s_start = cur.selBegin().idx();
5467                 row_type const row_start = tabular.cellRow(s_start);
5468                 row_type const row_end = tabular.cellRow(cur.selEnd().idx());
5469                 cur.idx() = tabular.setMultiRow(s_start, row_end - row_start + 1,
5470                                                 tabular.bottomLine(cur.selEnd().idx()));
5471                 cur.pit() = 0;
5472                 cur.pos() = 0;
5473                 cur.setSelection(false);
5474                 break;
5475         }
5476
5477         case Tabular::UNSET_MULTIROW: {
5478                 if (!cur.selection()) {
5479                         if (tabular.isMultiRow(cur.idx()))
5480                                 tabular.unsetMultiRow(cur.idx());
5481                 }
5482                 break;
5483         }
5484
5485         case Tabular::MULTIROW: {
5486                 if (!cur.selection()) {
5487                         if (tabular.isMultiRow(cur.idx()))
5488                                 tabularFeatures(cur, Tabular::UNSET_MULTIROW);
5489                         else
5490                                 tabularFeatures(cur, Tabular::SET_MULTIROW);
5491                         break;
5492                 }
5493                 bool merge = false;
5494                 for (row_type r = sel_row_start; r <= sel_row_end; ++r) {
5495                         col_type const c = sel_col_start;
5496                         if (!tabular.isMultiRow(tabular.cellIndex(r, c))
5497                             || (r > sel_row_start && !tabular.isPartOfMultiRow(r, c)))
5498                                 merge = true;
5499                 }
5500                 // If the selection contains at least one singlerow cell
5501                 // or multiple multirow cells,
5502                 // we assume the user will merge is to a single multirow
5503                 if (merge)
5504                         tabularFeatures(cur, Tabular::SET_MULTIROW);
5505                 else
5506                         tabularFeatures(cur, Tabular::UNSET_MULTIROW);
5507                 break;
5508         }
5509
5510         case Tabular::SET_ALL_LINES:
5511                 setLines = true;
5512         case Tabular::UNSET_ALL_LINES:
5513                 for (row_type r = sel_row_start; r <= sel_row_end; ++r)
5514                         for (col_type c = sel_col_start; c <= sel_col_end; ++c) {
5515                                 idx_type const cell = tabular.cellIndex(r, c);
5516                                 tabular.setTopLine(cell, setLines);
5517                                 tabular.setBottomLine(cell, setLines);
5518                                 tabular.setRightLine(cell, setLines);
5519                                 tabular.setLeftLine(cell, setLines);
5520                         }
5521                 break;
5522
5523         case Tabular::SET_BORDER_LINES:
5524                 for (row_type r = sel_row_start; r <= sel_row_end; ++r) {
5525                         tabular.setLeftLine(tabular.cellIndex(r, sel_col_start), true);
5526                         tabular.setRightLine(tabular.cellIndex(r, sel_col_end), true);
5527                 }
5528                 for (col_type c = sel_col_start; c <= sel_col_end; ++c) {
5529                         tabular.setTopLine(tabular.cellIndex(sel_row_start, c), true);
5530                         tabular.setBottomLine(tabular.cellIndex(sel_row_end, c), true);
5531                 }
5532                 break;
5533
5534         case Tabular::SET_LONGTABULAR:
5535                 tabular.is_long_tabular = true;
5536                 break;
5537
5538         case Tabular::UNSET_LONGTABULAR:
5539                 for (row_type r = 0; r < tabular.nrows(); ++r) {
5540                         if (tabular.ltCaption(r)) {
5541                                 cur.idx() = tabular.cellIndex(r, 0);
5542                                 cur.pit() = 0;
5543                                 cur.pos() = 0;
5544                                 tabularFeatures(cur, Tabular::TOGGLE_LTCAPTION);
5545                         }
5546                 }
5547                 tabular.is_long_tabular = false;
5548                 break;
5549
5550         case Tabular::SET_ROTATE_TABULAR:
5551                 tabular.rotate = true;
5552                 break;
5553
5554         case Tabular::UNSET_ROTATE_TABULAR:
5555                 tabular.rotate = false;
5556                 break;
5557
5558         case Tabular::TOGGLE_ROTATE_TABULAR:
5559                 tabular.rotate = !tabular.rotate;
5560                 break;
5561
5562         case Tabular::TABULAR_VALIGN_TOP:
5563                 tabular.tabular_valignment = Tabular::LYX_VALIGN_TOP;
5564                 break;
5565
5566         case Tabular::TABULAR_VALIGN_MIDDLE:
5567                 tabular.tabular_valignment = Tabular::LYX_VALIGN_MIDDLE;
5568                 break;
5569
5570         case Tabular::TABULAR_VALIGN_BOTTOM:
5571                 tabular.tabular_valignment = Tabular::LYX_VALIGN_BOTTOM;
5572                 break;
5573
5574         case Tabular::LONGTABULAR_ALIGN_LEFT:
5575                 tabular.longtabular_alignment = Tabular::LYX_LONGTABULAR_ALIGN_LEFT;
5576                 break;
5577
5578         case Tabular::LONGTABULAR_ALIGN_CENTER:
5579                 tabular.longtabular_alignment = Tabular::LYX_LONGTABULAR_ALIGN_CENTER;
5580                 break;
5581
5582         case Tabular::LONGTABULAR_ALIGN_RIGHT:
5583                 tabular.longtabular_alignment = Tabular::LYX_LONGTABULAR_ALIGN_RIGHT;
5584                 break;
5585
5586                 
5587
5588         case Tabular::SET_ROTATE_CELL:
5589                 for (row_type r = sel_row_start; r <= sel_row_end; ++r)
5590                         for (col_type c = sel_col_start; c <= sel_col_end; ++c)
5591                                 tabular.setRotateCell(tabular.cellIndex(r, c), true);
5592                 break;
5593
5594         case Tabular::UNSET_ROTATE_CELL:
5595                 for (row_type r = sel_row_start; r <= sel_row_end; ++r)
5596                         for (col_type c = sel_col_start; c <= sel_col_end; ++c)
5597                                 tabular.setRotateCell(tabular.cellIndex(r, c), false);
5598                 break;
5599
5600         case Tabular::TOGGLE_ROTATE_CELL:
5601                 {
5602                 bool oneNotRotated = oneCellHasRotationState(false,
5603                         sel_row_start, sel_row_end, sel_col_start, sel_col_end);
5604
5605                 for (row_type r = sel_row_start; r <= sel_row_end; ++r)
5606                         for (col_type c = sel_col_start; c <= sel_col_end; ++c)
5607                                 tabular.setRotateCell(tabular.cellIndex(r, c),
5608                                                                           oneNotRotated);
5609                 }
5610                 break;
5611
5612         case Tabular::SET_USEBOX: {
5613                 Tabular::BoxType val = Tabular::BoxType(convert<int>(value));
5614                 if (val == tabular.getUsebox(cur.idx()))
5615                         val = Tabular::BOX_NONE;
5616                 for (row_type r = sel_row_start; r <= sel_row_end; ++r)
5617                         for (col_type c = sel_col_start; c <= sel_col_end; ++c)
5618                                 tabular.setUsebox(tabular.cellIndex(r, c), val);
5619                 break;
5620         }
5621
5622         case Tabular::UNSET_LTFIRSTHEAD:
5623                 flag = false;
5624         case Tabular::SET_LTFIRSTHEAD:
5625                 tabular.getRowOfLTFirstHead(row, ltt);
5626                 checkLongtableSpecial(ltt, value, flag);
5627                 tabular.setLTHead(row, flag, ltt, true);
5628                 break;
5629
5630         case Tabular::UNSET_LTHEAD:
5631                 flag = false;
5632         case Tabular::SET_LTHEAD:
5633                 tabular.getRowOfLTHead(row, ltt);
5634                 checkLongtableSpecial(ltt, value, flag);
5635                 tabular.setLTHead(row, flag, ltt, false);
5636                 break;
5637
5638         case Tabular::UNSET_LTFOOT:
5639                 flag = false;
5640         case Tabular::SET_LTFOOT:
5641                 tabular.getRowOfLTFoot(row, ltt);
5642                 checkLongtableSpecial(ltt, value, flag);
5643                 tabular.setLTFoot(row, flag, ltt, false);
5644                 break;
5645
5646         case Tabular::UNSET_LTLASTFOOT:
5647                 flag = false;
5648         case Tabular::SET_LTLASTFOOT:
5649                 tabular.getRowOfLTLastFoot(row, ltt);
5650                 checkLongtableSpecial(ltt, value, flag);
5651                 tabular.setLTFoot(row, flag, ltt, true);
5652                 break;
5653
5654         case Tabular::SET_LTNEWPAGE:
5655                 tabular.setLTNewPage(row, !tabular.getLTNewPage(row));
5656                 break;
5657
5658         case Tabular::SET_LTCAPTION: {
5659                 if (tabular.ltCaption(row))
5660                         break;
5661                 cur.idx() = tabular.setLTCaption(row, true);
5662                 cur.pit() = 0;
5663                 cur.pos() = 0;
5664                 cur.setSelection(false);
5665                 // If a row is set as caption, then also insert
5666                 // a caption. Otherwise the LaTeX output is broken.
5667                 lyx::dispatch(FuncRequest(LFUN_INSET_SELECT_ALL));
5668                 lyx::dispatch(FuncRequest(LFUN_CAPTION_INSERT));
5669                 break;
5670         }
5671         
5672         case Tabular::UNSET_LTCAPTION: {
5673                 if (!tabular.ltCaption(row))
5674                         break;
5675                 cur.idx() = tabular.setLTCaption(row, false);
5676                 cur.pit() = 0;
5677                 cur.pos() = 0;
5678                 cur.setSelection(false);
5679                 FuncRequest fr(LFUN_INSET_DISSOLVE, "caption");
5680                 if (lyx::getStatus(fr).enabled())
5681                         lyx::dispatch(fr);
5682                 break;
5683         }
5684
5685         case Tabular::TOGGLE_LTCAPTION: {
5686                 if (tabular.ltCaption(row))
5687                         tabularFeatures(cur, Tabular::UNSET_LTCAPTION);
5688                 else
5689                         tabularFeatures(cur, Tabular::SET_LTCAPTION);
5690                 break;
5691         }
5692
5693         case Tabular::SET_BOOKTABS:
5694                 tabular.use_booktabs = true;
5695                 break;
5696
5697         case Tabular::UNSET_BOOKTABS:
5698                 tabular.use_booktabs = false;
5699                 break;
5700
5701         case Tabular::SET_TOP_SPACE: {
5702                 Length len;
5703                 if (value == "default")
5704                         for (row_type r = sel_row_start; r <= sel_row_end; ++r)
5705                                 tabular.row_info[r].top_space_default = true;
5706                 else if (value == "none")
5707                         for (row_type r = sel_row_start; r <= sel_row_end; ++r) {
5708                                 tabular.row_info[r].top_space_default = false;
5709                                 tabular.row_info[r].top_space = len;
5710                         }
5711                 else if (isValidLength(value, &len))
5712                         for (row_type r = sel_row_start; r <= sel_row_end; ++r) {
5713                                 tabular.row_info[r].top_space_default = false;
5714                                 tabular.row_info[r].top_space = len;
5715                         }
5716                 break;
5717         }
5718
5719         case Tabular::SET_BOTTOM_SPACE: {
5720                 Length len;
5721                 if (value == "default")
5722                         for (row_type r = sel_row_start; r <= sel_row_end; ++r)
5723                                 tabular.row_info[r].bottom_space_default = true;
5724                 else if (value == "none")
5725                         for (row_type r = sel_row_start; r <= sel_row_end; ++r) {
5726                                 tabular.row_info[r].bottom_space_default = false;
5727                                 tabular.row_info[r].bottom_space = len;
5728                         }
5729                 else if (isValidLength(value, &len))
5730                         for (row_type r = sel_row_start; r <= sel_row_end; ++r) {
5731                                 tabular.row_info[r].bottom_space_default = false;
5732                                 tabular.row_info[r].bottom_space = len;
5733                         }
5734                 break;
5735         }
5736
5737         case Tabular::SET_INTERLINE_SPACE: {
5738                 Length len;
5739                 if (value == "default")
5740                         for (row_type r = sel_row_start; r <= sel_row_end; ++r)
5741                                 tabular.row_info[r].interline_space_default = true;
5742                 else if (value == "none")
5743                         for (row_type r = sel_row_start; r <= sel_row_end; ++r) {
5744                                 tabular.row_info[r].interline_space_default = false;
5745                                 tabular.row_info[r].interline_space = len;
5746                         }
5747                 else if (isValidLength(value, &len))
5748                         for (row_type r = sel_row_start; r <= sel_row_end; ++r) {
5749                                 tabular.row_info[r].interline_space_default = false;
5750                                 tabular.row_info[r].interline_space = len;
5751                         }
5752                 break;
5753         }
5754
5755         case Tabular::SET_DECIMAL_POINT:
5756                 for (col_type c = sel_col_start; c <= sel_col_end; ++c)
5757                         tabular.column_info[c].decimal_point = from_utf8(value);
5758                 break;
5759
5760         // dummy stuff just to avoid warnings
5761         case Tabular::LAST_ACTION:
5762                 break;
5763         }
5764 }
5765
5766
5767 bool InsetTabular::copySelection(Cursor & cur)
5768 {
5769         if (!cur.selection())
5770                 return false;
5771
5772         row_type rs, re;
5773         col_type cs, ce;
5774         getSelection(cur, rs, re, cs, ce);
5775
5776         paste_tabular.reset(new Tabular(tabular));
5777
5778         for (row_type r = 0; r < rs; ++r)
5779                 paste_tabular->deleteRow(0);
5780
5781         row_type const rows = re - rs + 1;
5782         while (paste_tabular->nrows() > rows)
5783                 paste_tabular->deleteRow(rows);
5784
5785         for (col_type c = 0; c < cs; ++c)
5786                 paste_tabular->deleteColumn(0);
5787
5788         col_type const columns = ce - cs + 1;
5789         while (paste_tabular->ncols() > columns)
5790                 paste_tabular->deleteColumn(columns);
5791
5792         paste_tabular->setBuffer(tabular.buffer());
5793
5794         odocstringstream os;
5795         OutputParams const runparams(0);
5796         paste_tabular->plaintext(os, runparams, 0, true, '\t');
5797         // Needed for the "Edit->Paste recent" menu and the system clipboard.
5798         cap::copySelection(cur, os.str());
5799
5800         // mark tabular stack dirty
5801         // FIXME: this is a workaround for bug 1919. Should be removed for 1.5,
5802         // when we (hopefully) have a one-for-all paste mechanism.
5803         // This must be called after cap::copySelection.
5804         dirtyTabularStack(true);
5805
5806         return true;
5807 }
5808
5809
5810 bool InsetTabular::pasteClipboard(Cursor & cur)
5811 {
5812         if (!paste_tabular)
5813                 return false;
5814         col_type actcol = tabular.cellColumn(cur.idx());
5815         row_type actrow = tabular.cellRow(cur.idx());
5816
5817         if (cur.selIsMultiCell()) {
5818                 row_type re;
5819                 col_type ce;
5820                 getSelection(cur, actrow, re, actcol, ce);
5821         }
5822
5823         for (row_type r1 = 0, r2 = actrow;
5824              r1 < paste_tabular->nrows() && r2 < tabular.nrows();
5825              ++r1, ++r2) {
5826                 for (col_type c1 = 0, c2 = actcol;
5827                     c1 < paste_tabular->ncols() && c2 < tabular.ncols();
5828                     ++c1, ++c2) {
5829                         if (paste_tabular->isPartOfMultiColumn(r1, c1) &&
5830                               tabular.isPartOfMultiColumn(r2, c2))
5831                                 continue;
5832                         if (paste_tabular->isPartOfMultiColumn(r1, c1)) {
5833                                 --c2;
5834                                 continue;
5835                         }
5836                         if (tabular.isPartOfMultiColumn(r2, c2)) {
5837                                 --c1;
5838                                 continue;
5839                         }
5840                         shared_ptr<InsetTableCell> inset(
5841                                 new InsetTableCell(*paste_tabular->cellInset(r1, c1)));
5842                         tabular.setCellInset(r2, c2, inset);
5843                         // FIXME?: why do we need to do this explicitly? (EL)
5844                         tabular.cellInset(r2, c2)->setBuffer(tabular.buffer());
5845
5846                         // FIXME: change tracking (MG)
5847                         inset->setChange(Change(buffer().params().trackChanges ?
5848                                                 Change::INSERTED : Change::UNCHANGED));
5849                         cur.pos() = 0;
5850                 }
5851         }
5852         return true;
5853 }
5854
5855
5856 void InsetTabular::cutSelection(Cursor & cur)
5857 {
5858         if (!cur.selection())
5859                 return;
5860
5861         row_type rs, re;
5862         col_type cs, ce;
5863         getSelection(cur, rs, re, cs, ce);
5864         for (row_type r = rs; r <= re; ++r) {
5865                 for (col_type c = cs; c <= ce; ++c) {
5866                         shared_ptr<InsetTableCell> t
5867                                 = cell(tabular.cellIndex(r, c));
5868                         if (buffer().params().trackChanges)
5869                                 // FIXME: Change tracking (MG)
5870                                 t->setChange(Change(Change::DELETED));
5871                         else
5872                                 t->clear();
5873                 }
5874         }
5875
5876         // cursor position might be invalid now
5877         if (cur.pit() > cur.lastpit())
5878                 cur.pit() = cur.lastpit();
5879         if (cur.pos() > cur.lastpos())
5880                 cur.pos() = cur.lastpos();
5881         cur.clearSelection();
5882 }
5883
5884
5885 bool InsetTabular::isRightToLeft(Cursor & cur) const
5886 {
5887         LASSERT(cur.depth() > 1, /**/);
5888         Paragraph const & parentpar = cur[cur.depth() - 2].paragraph();
5889         pos_type const parentpos = cur[cur.depth() - 2].pos();
5890         return parentpar.getFontSettings(buffer().params(),
5891                                          parentpos).language()->rightToLeft();
5892 }
5893
5894
5895 docstring InsetTabular::asString(idx_type stidx, idx_type enidx, 
5896                                  bool intoInsets)
5897 {
5898         LASSERT(stidx <= enidx, return docstring());
5899         docstring retval;
5900         col_type const col1 = tabular.cellColumn(stidx);
5901         col_type const col2 = tabular.cellColumn(enidx);
5902         row_type const row1 = tabular.cellRow(stidx);
5903         row_type const row2 = tabular.cellRow(enidx);
5904         bool first = true;
5905         for (col_type col = col1; col <= col2; col++)
5906                 for (row_type row = row1; row <= row2; row++) {
5907                         if (!first)
5908                                 retval += "\n";
5909                         else
5910                                 first = false;
5911                         retval += tabular.cellInset(row, col)->asString(intoInsets);
5912                 }
5913         return retval;
5914 }
5915
5916
5917 void InsetTabular::getSelection(Cursor & cur,
5918         row_type & rs, row_type & re, col_type & cs, col_type & ce) const
5919 {
5920         CursorSlice const & beg = cur.selBegin();
5921         CursorSlice const & end = cur.selEnd();
5922         cs = tabular.cellColumn(beg.idx());
5923         ce = tabular.cellColumn(end.idx());
5924         if (cs > ce)
5925                 swap(cs, ce);
5926
5927         rs = tabular.cellRow(beg.idx());
5928         re = tabular.cellRow(end.idx());
5929         if (rs > re)
5930                 swap(rs, re);
5931 }
5932
5933
5934 Text * InsetTabular::getText(int idx) const
5935 {
5936         return size_t(idx) < nargs() ? cell(idx)->getText(0) : 0;
5937 }
5938
5939
5940 void InsetTabular::setChange(Change const & change)
5941 {
5942         for (idx_type idx = 0; idx < nargs(); ++idx)
5943                 cell(idx)->setChange(change);
5944 }
5945
5946
5947 void InsetTabular::acceptChanges()
5948 {
5949         for (idx_type idx = 0; idx < nargs(); ++idx)
5950                 cell(idx)->acceptChanges();
5951 }
5952
5953
5954 void InsetTabular::rejectChanges()
5955 {
5956         for (idx_type idx = 0; idx < nargs(); ++idx)
5957                 cell(idx)->rejectChanges();
5958 }
5959
5960
5961 bool InsetTabular::allowParagraphCustomization(idx_type cell) const
5962 {
5963         return tabular.getPWidth(cell).zero();
5964 }
5965
5966
5967 bool InsetTabular::forcePlainLayout(idx_type cell) const
5968 {
5969         return !tabular.getPWidth(cell).zero();
5970 }
5971
5972
5973 bool InsetTabular::insertPlaintextString(BufferView & bv, docstring const & buf,
5974                                      bool usePaste)
5975 {
5976         if (buf.length() <= 0)
5977                 return true;
5978
5979         col_type cols = 1;
5980         row_type rows = 1;
5981         col_type maxCols = 1;
5982         size_t const len = buf.length();
5983         size_t p = 0;
5984
5985         while (p < len &&
5986                (p = buf.find_first_of(from_ascii("\t\n"), p)) != docstring::npos) {
5987                 switch (buf[p]) {
5988                 case '\t':
5989                         ++cols;
5990                         break;
5991                 case '\n':
5992                         if (p + 1 < len)
5993                                 ++rows;
5994                         maxCols = max(cols, maxCols);
5995                         cols = 1;
5996                         break;
5997                 }
5998                 ++p;
5999         }
6000         maxCols = max(cols, maxCols);
6001         Tabular * loctab;
6002         idx_type cell = 0;
6003         col_type ocol = 0;
6004         row_type row = 0;
6005         if (usePaste) {
6006                 paste_tabular.reset(new Tabular(buffer_, rows, maxCols));
6007                 loctab = paste_tabular.get();
6008                 cols = 0;
6009                 dirtyTabularStack(true);
6010         } else {
6011                 loctab = &tabular;
6012                 cell = bv.cursor().idx();
6013                 ocol = tabular.cellColumn(cell);
6014                 row = tabular.cellRow(cell);
6015         }
6016
6017         size_t op = 0;
6018         idx_type const cells = loctab->numberofcells;
6019         p = 0;
6020         cols = ocol;
6021         rows = loctab->nrows();
6022         col_type const columns = loctab->ncols();
6023
6024         while (cell < cells && p < len && row < rows &&
6025                (p = buf.find_first_of(from_ascii("\t\n"), p)) != docstring::npos)
6026         {
6027                 if (p >= len)
6028                         break;
6029                 switch (buf[p]) {
6030                 case '\t':
6031                         // we can only set this if we are not too far right
6032                         if (cols < columns) {
6033                                 shared_ptr<InsetTableCell> inset = loctab->cellInset(cell);
6034                                 Font const font = bv.textMetrics(&inset->text()).
6035                                         displayFont(0, 0);
6036                                 inset->setText(buf.substr(op, p - op), font,
6037                                                buffer().params().trackChanges);
6038                                 ++cols;
6039                                 ++cell;
6040                         }
6041                         break;
6042                 case '\n':
6043                         // we can only set this if we are not too far right
6044                         if (cols < columns) {
6045                                 shared_ptr<InsetTableCell> inset = tabular.cellInset(cell);
6046                                 Font const font = bv.textMetrics(&inset->text()).
6047                                         displayFont(0, 0);
6048                                 inset->setText(buf.substr(op, p - op), font,
6049                                                buffer().params().trackChanges);
6050                         }
6051                         cols = ocol;
6052                         ++row;
6053                         if (row < rows)
6054                                 cell = loctab->cellIndex(row, cols);
6055                         break;
6056                 }
6057                 ++p;
6058                 op = p;
6059         }
6060         // check for the last cell if there is no trailing '\n'
6061         if (cell < cells && op < len) {
6062                 shared_ptr<InsetTableCell> inset = loctab->cellInset(cell);
6063                 Font const font = bv.textMetrics(&inset->text()).displayFont(0, 0);
6064                 inset->setText(buf.substr(op, len - op), font,
6065                         buffer().params().trackChanges);
6066         }
6067         return true;
6068 }
6069
6070
6071 void InsetTabular::addPreview(DocIterator const & inset_pos,
6072         PreviewLoader & loader) const
6073 {
6074         DocIterator cell_pos = inset_pos;
6075
6076         cell_pos.push_back(CursorSlice(*const_cast<InsetTabular *>(this)));
6077         for (row_type r = 0; r < tabular.nrows(); ++r) {
6078                 for (col_type c = 0; c < tabular.ncols(); ++c) {
6079                         cell_pos.top().idx() = tabular.cellIndex(r, c);
6080                         tabular.cellInset(r, c)->addPreview(cell_pos, loader);
6081                 }
6082         }
6083 }
6084
6085
6086 bool InsetTabular::completionSupported(Cursor const & cur) const
6087 {
6088         Cursor const & bvCur = cur.bv().cursor();
6089         if (&bvCur.inset() != this)
6090                 return false;
6091         return cur.text()->completionSupported(cur);
6092 }
6093
6094
6095 bool InsetTabular::inlineCompletionSupported(Cursor const & cur) const
6096 {
6097         return completionSupported(cur);
6098 }
6099
6100
6101 bool InsetTabular::automaticInlineCompletion() const
6102 {
6103         return lyxrc.completion_inline_text;
6104 }
6105
6106
6107 bool InsetTabular::automaticPopupCompletion() const
6108 {
6109         return lyxrc.completion_popup_text;
6110 }
6111
6112
6113 bool InsetTabular::showCompletionCursor() const
6114 {
6115         return lyxrc.completion_cursor_text;
6116 }
6117
6118
6119 CompletionList const * InsetTabular::createCompletionList(Cursor const & cur) const
6120 {
6121         return completionSupported(cur) ? cur.text()->createCompletionList(cur) : 0;
6122 }
6123
6124
6125 docstring InsetTabular::completionPrefix(Cursor const & cur) const
6126 {
6127         if (!completionSupported(cur))
6128                 return docstring();
6129         return cur.text()->completionPrefix(cur);
6130 }
6131
6132
6133 bool InsetTabular::insertCompletion(Cursor & cur, docstring const & s, bool finished)
6134 {
6135         if (!completionSupported(cur))
6136                 return false;
6137
6138         return cur.text()->insertCompletion(cur, s, finished);
6139 }
6140
6141
6142 void InsetTabular::completionPosAndDim(Cursor const & cur, int & x, int & y, 
6143                                     Dimension & dim) const
6144 {
6145         TextMetrics const & tm = cur.bv().textMetrics(cur.text());
6146         tm.completionPosAndDim(cur, x, y, dim);
6147 }
6148
6149
6150 void InsetTabular::string2params(string const & in, InsetTabular & inset)
6151 {
6152         istringstream data(in);
6153         Lexer lex;
6154         lex.setStream(data);
6155
6156         if (in.empty())
6157                 return;
6158
6159         string token;
6160         lex >> token;
6161         if (!lex || token != "tabular") {
6162                 LYXERR0("Expected arg 1 to be \"tabular\" in " << in);
6163                 return;
6164         }
6165
6166         // This is part of the inset proper that is usually swallowed
6167         // by Buffer::readInset
6168         lex >> token;
6169         if (!lex || token != "Tabular") {
6170                 LYXERR0("Expected arg 2 to be \"Tabular\" in " << in);
6171                 return;
6172         }
6173
6174         inset.read(lex);
6175 }
6176
6177
6178 string InsetTabular::params2string(InsetTabular const & inset)
6179 {
6180         ostringstream data;
6181         data << "tabular" << ' ';
6182         inset.write(data);
6183         data << "\\end_inset\n";
6184         return data.str();
6185 }
6186
6187
6188 } // namespace lyx