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