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