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