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