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