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