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