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