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