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