]> git.lyx.org Git - features.git/blob - src/insets/InsetTabular.cpp
Table cells are insets, but not from the point of view of DocIterators
[features.git] / src / insets / InsetTabular.cpp
1 /**
2  * \file InsetTabular.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Lars Gullik Bjønnes
7  * \author Matthias Ettrich
8  * \author José Matos
9  * \author Jean-Marc Lasgouttes
10  * \author Angus Leeming
11  * \author John Levon
12  * \author André Pönitz
13  * \author Jürgen Vigna
14  * \author Uwe Stöhr
15  * \author Edwin Leuven
16  * \author Scott Kostyshak
17  *
18  * Full author contact details are available in file CREDITS.
19  */
20
21 #include <config.h>
22
23 #include "InsetTabular.h"
24
25 #include "buffer_funcs.h"
26 #include "Buffer.h"
27 #include "BufferParams.h"
28 #include "BufferView.h"
29 #include "CoordCache.h"
30 #include "Counters.h"
31 #include "Cursor.h"
32 #include "CutAndPaste.h"
33 #include "DispatchResult.h"
34 #include "FuncRequest.h"
35 #include "FuncStatus.h"
36 #include "InsetList.h"
37 #include "Language.h"
38 #include "LaTeXFeatures.h"
39 #include "Lexer.h"
40 #include "LyX.h"
41 #include "LyXRC.h"
42 #include "MetricsInfo.h"
43 #include "OutputParams.h"
44 #include "output_xhtml.h"
45 #include "Paragraph.h"
46 #include "ParagraphParameters.h"
47 #include "ParIterator.h"
48 #include "TextClass.h"
49 #include "TextMetrics.h"
50
51 #include "frontends/Application.h"
52 #include "frontends/alert.h"
53 #include "frontends/Clipboard.h"
54 #include "frontends/Painter.h"
55 #include "frontends/Selection.h"
56
57 #include "support/convert.h"
58 #include "support/debug.h"
59 #include "support/docstream.h"
60 #include "support/FileName.h"
61 #include "support/gettext.h"
62 #include "support/lassert.h"
63 #include "support/lstrings.h"
64
65 #include <boost/scoped_ptr.hpp>
66
67 #include <cstring>
68 #include <iostream>
69 #include <limits>
70 #include <sstream>
71
72 using namespace std;
73 using namespace lyx::support;
74
75
76
77 namespace lyx {
78
79 using cap::dirtyTabularStack;
80 using cap::tabularStackDirty;
81
82 using graphics::PreviewLoader;
83
84 using frontend::Painter;
85 using frontend::Clipboard;
86
87 namespace Alert = frontend::Alert;
88
89
90 namespace {
91
92 int const ADD_TO_HEIGHT = 2; // in cell
93 int const ADD_TO_TABULAR_WIDTH = 6; // horizontal space before and after the table
94 int const default_line_space = 10; // ?
95 int const WIDTH_OF_LINE = 5; // space between double lines
96
97
98 ///
99 boost::scoped_ptr<Tabular> paste_tabular;
100
101
102 struct TabularFeature {
103         Tabular::Feature action;
104         string feature;
105         bool need_value;
106 };
107
108
109 TabularFeature tabularFeature[] =
110 {
111         // the SET/UNSET actions are used by the table dialog,
112         // the TOGGLE actions by the table toolbar buttons
113         { Tabular::APPEND_ROW, "append-row", false },
114         { Tabular::APPEND_COLUMN, "append-column", false },
115         { Tabular::DELETE_ROW, "delete-row", false },
116         { Tabular::DELETE_COLUMN, "delete-column", false },
117         { Tabular::COPY_ROW, "copy-row", false },
118         { Tabular::COPY_COLUMN, "copy-column", false },
119         { Tabular::MOVE_COLUMN_RIGHT, "move-column-right", false },
120         { Tabular::MOVE_COLUMN_LEFT, "move-column-left", false },
121         { Tabular::MOVE_ROW_DOWN, "move-row-down", false },
122         { Tabular::MOVE_ROW_UP, "move-row-up", false },
123         { Tabular::SET_LINE_TOP, "set-line-top", true },
124         { Tabular::SET_LINE_BOTTOM, "set-line-bottom", true },
125         { Tabular::SET_LINE_LEFT, "set-line-left", true },
126         { Tabular::SET_LINE_RIGHT, "set-line-right", true },
127         { Tabular::TOGGLE_LINE_TOP, "toggle-line-top", false },
128         { Tabular::TOGGLE_LINE_BOTTOM, "toggle-line-bottom", false },
129         { Tabular::TOGGLE_LINE_LEFT, "toggle-line-left", false },
130         { Tabular::TOGGLE_LINE_RIGHT, "toggle-line-right", false },
131         { Tabular::ALIGN_LEFT, "align-left", false },
132         { Tabular::ALIGN_RIGHT, "align-right", false },
133         { Tabular::ALIGN_CENTER, "align-center", false },
134         { Tabular::ALIGN_BLOCK, "align-block", false },
135         { Tabular::ALIGN_DECIMAL, "align-decimal", false },
136         { Tabular::VALIGN_TOP, "valign-top", false },
137         { Tabular::VALIGN_BOTTOM, "valign-bottom", false },
138         { Tabular::VALIGN_MIDDLE, "valign-middle", false },
139         { Tabular::M_ALIGN_LEFT, "m-align-left", false },
140         { Tabular::M_ALIGN_RIGHT, "m-align-right", false },
141         { Tabular::M_ALIGN_CENTER, "m-align-center", false },
142         { Tabular::M_VALIGN_TOP, "m-valign-top", false },
143         { Tabular::M_VALIGN_BOTTOM, "m-valign-bottom", false },
144         { Tabular::M_VALIGN_MIDDLE, "m-valign-middle", false },
145         { Tabular::MULTICOLUMN, "multicolumn", false },
146         { Tabular::SET_MULTICOLUMN, "set-multicolumn", false },
147         { Tabular::UNSET_MULTICOLUMN, "unset-multicolumn", false },
148         { Tabular::MULTIROW, "multirow", false },
149         { Tabular::SET_MULTIROW, "set-multirow", false },
150         { Tabular::UNSET_MULTIROW, "unset-multirow", false },
151         { Tabular::SET_MROFFSET, "set-mroffset", true },
152         { Tabular::SET_ALL_LINES, "set-all-lines", false },
153         { Tabular::UNSET_ALL_LINES, "unset-all-lines", false },
154         { Tabular::SET_LONGTABULAR, "set-longtabular", false },
155         { Tabular::UNSET_LONGTABULAR, "unset-longtabular", false },
156         { Tabular::SET_PWIDTH, "set-pwidth", true },
157         { Tabular::SET_MPWIDTH, "set-mpwidth", true },
158         { Tabular::SET_ROTATE_TABULAR, "set-rotate-tabular", true },
159         { Tabular::UNSET_ROTATE_TABULAR, "unset-rotate-tabular", true },
160         { Tabular::TOGGLE_ROTATE_TABULAR, "toggle-rotate-tabular", true },
161         { Tabular::SET_ROTATE_CELL, "set-rotate-cell", true },
162         { Tabular::UNSET_ROTATE_CELL, "unset-rotate-cell", true },
163         { Tabular::TOGGLE_ROTATE_CELL, "toggle-rotate-cell", true },
164         { Tabular::SET_USEBOX, "set-usebox", true },
165         { Tabular::SET_LTHEAD, "set-lthead", true },
166         { Tabular::UNSET_LTHEAD, "unset-lthead", true },
167         { Tabular::SET_LTFIRSTHEAD, "set-ltfirsthead", true },
168         { Tabular::UNSET_LTFIRSTHEAD, "unset-ltfirsthead", true },
169         { Tabular::SET_LTFOOT, "set-ltfoot", true },
170         { Tabular::UNSET_LTFOOT, "unset-ltfoot", true },
171         { Tabular::SET_LTLASTFOOT, "set-ltlastfoot", true },
172         { Tabular::UNSET_LTLASTFOOT, "unset-ltlastfoot", true },
173         { Tabular::SET_LTNEWPAGE, "set-ltnewpage", false },
174         { Tabular::UNSET_LTNEWPAGE, "unset-ltnewpage", false },
175         { Tabular::TOGGLE_LTCAPTION, "toggle-ltcaption", false },
176         { Tabular::SET_LTCAPTION, "set-ltcaption", false },
177         { Tabular::UNSET_LTCAPTION, "unset-ltcaption", false },
178         { Tabular::SET_SPECIAL_COLUMN, "set-special-column", true },
179         { Tabular::SET_SPECIAL_MULTICOLUMN, "set-special-multicolumn", true },
180         { Tabular::SET_BOOKTABS, "set-booktabs", false },
181         { Tabular::UNSET_BOOKTABS, "unset-booktabs", false },
182         { Tabular::SET_TOP_SPACE, "set-top-space", true },
183         { Tabular::SET_BOTTOM_SPACE, "set-bottom-space", true },
184         { Tabular::SET_INTERLINE_SPACE, "set-interline-space", true },
185         { Tabular::SET_BORDER_LINES, "set-border-lines", false },
186         { Tabular::TABULAR_VALIGN_TOP, "tabular-valign-top", false},
187         { Tabular::TABULAR_VALIGN_MIDDLE, "tabular-valign-middle", false},
188         { Tabular::TABULAR_VALIGN_BOTTOM, "tabular-valign-bottom", false},
189         { Tabular::LONGTABULAR_ALIGN_LEFT, "longtabular-align-left", false },
190         { Tabular::LONGTABULAR_ALIGN_CENTER, "longtabular-align-center", false },
191         { Tabular::LONGTABULAR_ALIGN_RIGHT, "longtabular-align-right", false },
192         { Tabular::SET_DECIMAL_POINT, "set-decimal-point", true },
193         { Tabular::SET_TABULAR_WIDTH, "set-tabular-width", true },
194         { Tabular::LAST_ACTION, "", false }
195 };
196
197
198 string const tostr(LyXAlignment const & num)
199 {
200         switch (num) {
201         case LYX_ALIGN_NONE:
202                 return "none";
203         case LYX_ALIGN_BLOCK:
204                 return "block";
205         case LYX_ALIGN_LEFT:
206                 return "left";
207         case LYX_ALIGN_CENTER:
208                 return "center";
209         case LYX_ALIGN_RIGHT:
210                 return "right";
211         case LYX_ALIGN_LAYOUT:
212                 return "layout";
213         case LYX_ALIGN_SPECIAL:
214                 return "special";
215         case LYX_ALIGN_DECIMAL:
216                 return "decimal";
217         }
218         return string();
219 }
220
221
222 string const tostr(Tabular::HAlignment const & num)
223 {
224         switch (num) {
225         case Tabular::LYX_LONGTABULAR_ALIGN_LEFT:
226                 return "left";
227         case Tabular::LYX_LONGTABULAR_ALIGN_CENTER:
228                 return "center";
229         case Tabular::LYX_LONGTABULAR_ALIGN_RIGHT:
230                 return "right";
231         }
232         return string();
233 }
234
235
236 string const tostr(Tabular::VAlignment const & num)
237 {
238         switch (num) {
239         case Tabular::LYX_VALIGN_TOP:
240                 return "top";
241         case Tabular::LYX_VALIGN_MIDDLE:
242                 return "middle";
243         case Tabular::LYX_VALIGN_BOTTOM:
244                 return "bottom";
245         }
246         return string();
247 }
248
249
250 string const tostr(Tabular::BoxType const & num)
251 {
252         switch (num) {
253         case Tabular::BOX_NONE:
254                 return "none";
255         case Tabular::BOX_PARBOX:
256                 return "parbox";
257         case Tabular::BOX_MINIPAGE:
258                 return "minipage";
259         }
260         return string();
261 }
262
263
264 // I would have liked a fromstr template a lot better. (Lgb)
265 bool string2type(string const str, LyXAlignment & num)
266 {
267         if (str == "none")
268                 num = LYX_ALIGN_NONE;
269         else if (str == "block")
270                 num = LYX_ALIGN_BLOCK;
271         else if (str == "left")
272                 num = LYX_ALIGN_LEFT;
273         else if (str == "center")
274                 num = LYX_ALIGN_CENTER;
275         else if (str == "right")
276                 num = LYX_ALIGN_RIGHT;
277         else if (str == "decimal")
278                 num = LYX_ALIGN_DECIMAL;
279         else
280                 return false;
281         return true;
282 }
283
284
285 bool string2type(string const str, Tabular::HAlignment & num)
286 {
287         if (str == "left")
288                 num = Tabular::LYX_LONGTABULAR_ALIGN_LEFT;
289         else if (str == "center" )
290                 num = Tabular::LYX_LONGTABULAR_ALIGN_CENTER;
291         else if (str == "right")
292                 num = Tabular::LYX_LONGTABULAR_ALIGN_RIGHT;
293         else
294                 return false;
295         return true;
296 }
297
298
299 bool string2type(string const str, Tabular::VAlignment & num)
300 {
301         if (str == "top")
302                 num = Tabular::LYX_VALIGN_TOP;
303         else if (str == "middle" )
304                 num = Tabular::LYX_VALIGN_MIDDLE;
305         else if (str == "bottom")
306                 num = Tabular::LYX_VALIGN_BOTTOM;
307         else
308                 return false;
309         return true;
310 }
311
312
313 bool string2type(string const str, Tabular::BoxType & num)
314 {
315         if (str == "none")
316                 num = Tabular::BOX_NONE;
317         else if (str == "parbox")
318                 num = Tabular::BOX_PARBOX;
319         else if (str == "minipage")
320                 num = Tabular::BOX_MINIPAGE;
321         else
322                 return false;
323         return true;
324 }
325
326
327 bool string2type(string const str, bool & num)
328 {
329         if (str == "true")
330                 num = true;
331         else if (str == "false")
332                 num = false;
333         else
334                 return false;
335         return true;
336 }
337
338
339 bool getTokenValue(string const & str, char const * token, string & ret)
340 {
341         ret.erase();
342         size_t token_length = strlen(token);
343         size_t pos = str.find(token);
344
345         if (pos == string::npos || pos + token_length + 1 >= str.length()
346                 || str[pos + token_length] != '=')
347                 return false;
348         pos += token_length + 1;
349         char ch = str[pos];
350         if (ch != '"' && ch != '\'') { // only read till next space
351                 ret += ch;
352                 ch = ' ';
353         }
354         while (pos < str.length() - 1 && str[++pos] != ch)
355                 ret += str[pos];
356
357         return true;
358 }
359
360
361 bool getTokenValue(string const & str, char const * token, docstring & ret)
362 {
363         string tmp;
364         bool const success = getTokenValue(str, token, tmp);
365         ret = from_utf8(tmp);
366         return success;
367 }
368
369
370 bool getTokenValue(string const & str, char const * token, int & num)
371 {
372         string tmp;
373         num = 0;
374         if (!getTokenValue(str, token, tmp))
375                 return false;
376         num = convert<int>(tmp);
377         return true;
378 }
379
380
381 bool getTokenValue(string const & str, char const * token, LyXAlignment & num)
382 {
383         string tmp;
384         return getTokenValue(str, token, tmp) && string2type(tmp, num);
385 }
386
387
388 bool getTokenValue(string const & str, char const * token,
389                                    Tabular::HAlignment & num)
390 {
391         string tmp;
392         return getTokenValue(str, token, tmp) && string2type(tmp, num);
393 }
394
395
396 bool getTokenValue(string const & str, char const * token,
397                                    Tabular::VAlignment & num)
398 {
399         string tmp;
400         return getTokenValue(str, token, tmp) && string2type(tmp, num);
401 }
402
403
404 bool getTokenValue(string const & str, char const * token,
405                                    Tabular::BoxType & num)
406 {
407         string tmp;
408         return getTokenValue(str, token, tmp) && string2type(tmp, num);
409 }
410
411
412 bool getTokenValue(string const & str, char const * token, bool & flag)
413 {
414         // set the flag always to false as this should be the default for bools
415         // not in the file-format.
416         flag = false;
417         string tmp;
418         return getTokenValue(str, token, tmp) && string2type(tmp, flag);
419 }
420
421
422 bool getTokenValue(string const & str, char const * token, Length & len)
423 {
424         // set the length to be zero() as default as this it should be if not
425         // in the file format.
426         len = Length();
427         string tmp;
428         return getTokenValue(str, token, tmp) && isValidLength(tmp, &len);
429 }
430
431
432 bool getTokenValue(string const & str, char const * token, Length & len, bool & flag)
433 {
434         len = Length();
435         flag = false;
436         string tmp;
437         if (!getTokenValue(str, token, tmp))
438                 return false;
439         if (tmp == "default") {
440                 flag = true;
441                 return  true;
442         }
443         return isValidLength(tmp, &len);
444 }
445
446
447 void l_getline(istream & is, string & str)
448 {
449         str.erase();
450         while (str.empty()) {
451                 getline(is, str);
452                 if (!str.empty() && str[str.length() - 1] == '\r')
453                         str.erase(str.length() - 1);
454         }
455 }
456
457 template <class T>
458 string const write_attribute(string const & name, T const & t)
459 {
460         string const s = tostr(t);
461         return s.empty() ? s : " " + name + "=\"" + s + "\"";
462 }
463
464 template <>
465 string const write_attribute(string const & name, string const & t)
466 {
467         return t.empty() ? t : " " + name + "=\"" + t + "\"";
468 }
469
470
471 template <>
472 string const write_attribute(string const & name, docstring const & t)
473 {
474         return t.empty() ? string() : " " + name + "=\"" + to_utf8(t) + "\"";
475 }
476
477
478 template <>
479 string const write_attribute(string const & name, bool const & b)
480 {
481         // we write only true attribute values so we remove a bit of the
482         // file format bloat for tabulars.
483         return b ? write_attribute(name, convert<string>(b)) : string();
484 }
485
486
487 template <>
488 string const write_attribute(string const & name, int const & i)
489 {
490         // we write only true attribute values so we remove a bit of the
491         // file format bloat for tabulars.
492         return i ? write_attribute(name, convert<string>(i)) : string();
493 }
494
495
496 template <>
497 string const write_attribute(string const & name, Tabular::idx_type const & i)
498 {
499         // we write only true attribute values so we remove a bit of the
500         // file format bloat for tabulars.
501         return i ? write_attribute(name, convert<string>(i)) : string();
502 }
503
504
505 template <>
506 string const write_attribute(string const & name, Length const & value)
507 {
508         // we write only the value if we really have one same reson as above.
509         return value.zero() ? string() : write_attribute(name, value.asString());
510 }
511
512 } // namespace
513
514
515 string const featureAsString(Tabular::Feature action)
516 {
517         for (size_t i = 0; i != Tabular::LAST_ACTION; ++i) {
518                 if (tabularFeature[i].action == action)
519                         return tabularFeature[i].feature;
520         }
521         return string();
522 }
523
524
525 DocIterator separatorPos(InsetTableCell * cell, docstring const & align_d)
526 {
527         DocIterator dit = doc_iterator_begin(&(cell->buffer()), cell);
528         for (; dit; dit.forwardChar())
529                 if (dit.inTexted() && dit.depth() == 1
530                         && dit.paragraph().find(align_d, false, false, dit.pos()))
531                         break;
532
533         return dit;
534 }
535
536
537 InsetTableCell splitCell(InsetTableCell & head, docstring const align_d, bool & hassep)
538 {
539         InsetTableCell tail = InsetTableCell(head);
540         DocIterator const dit = separatorPos(&head, align_d);
541         hassep = dit;
542         if (hassep) {
543                 pit_type const psize = head.paragraphs().front().size();
544                 head.paragraphs().front().eraseChars(dit.pos(), psize, false);
545                 tail.paragraphs().front().eraseChars(0, 
546                         dit.pos() < psize ? dit.pos() + 1 : psize, false);
547         }
548
549         return tail;
550 }
551
552
553 /////////////////////////////////////////////////////////////////////
554 //
555 // Tabular
556 //
557 /////////////////////////////////////////////////////////////////////
558
559
560 Tabular::CellData::CellData(Buffer * buf)
561         : cellno(0),
562           width(0),
563           multicolumn(Tabular::CELL_NORMAL),
564           multirow(Tabular::CELL_NORMAL),
565           alignment(LYX_ALIGN_CENTER),
566           valignment(LYX_VALIGN_TOP),
567           decimal_hoffset(0),
568           decimal_width(0),
569           voffset(0),
570           top_line(false),
571           bottom_line(false),
572           left_line(false),
573           right_line(false),
574           usebox(BOX_NONE),
575           rotate(0),
576           inset(new InsetTableCell(buf))
577 {
578         inset->setBuffer(*buf);
579 }
580
581
582 Tabular::CellData::CellData(CellData const & cs)
583         : cellno(cs.cellno),
584           width(cs.width),
585           multicolumn(cs.multicolumn),
586           multirow(cs.multirow),
587           mroffset(cs.mroffset),
588           alignment(cs.alignment),
589           valignment(cs.valignment),
590           decimal_hoffset(cs.decimal_hoffset),
591           decimal_width(cs.decimal_width),
592           voffset(cs.voffset),
593           top_line(cs.top_line),
594           bottom_line(cs.bottom_line),
595           left_line(cs.left_line),
596           right_line(cs.right_line),
597           usebox(cs.usebox),
598           rotate(cs.rotate),
599           align_special(cs.align_special),
600           p_width(cs.p_width),
601           inset(static_cast<InsetTableCell *>(cs.inset->clone()))
602 {
603 }
604
605 Tabular::CellData & Tabular::CellData::operator=(CellData 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         // output caption which is in no header or footer
2455         if (haveLTCaption()) {
2456                 for (row_type r = 0; r < nrows(); ++r) {
2457                         if (row_info[r].caption &&
2458                             !row_info[r].endfirsthead && !row_info[r].endhead &&
2459                             !row_info[r].endfoot && !row_info[r].endlastfoot)
2460                                 TeXRow(os, r, runparams);
2461                 }
2462         }
2463         // output first header info
2464         if (haveLTFirstHead()) {
2465                 if (endfirsthead.topDL)
2466                         os << "\\hline\n";
2467                 for (row_type r = 0; r < nrows(); ++r) {
2468                         if (row_info[r].endfirsthead)
2469                                 TeXRow(os, r, runparams);
2470                 }
2471                 if (endfirsthead.bottomDL)
2472                         os << "\\hline\n";
2473                 os << "\\endfirsthead\n";
2474         }
2475         // output header info
2476         if (haveLTHead()) {
2477                 if (endfirsthead.empty && !haveLTFirstHead())
2478                         os << "\\endfirsthead\n";
2479                 if (endhead.topDL)
2480                         os << "\\hline\n";
2481                 for (row_type r = 0; r < nrows(); ++r) {
2482                         if (row_info[r].endhead)
2483                                 TeXRow(os, r, runparams);
2484                 }
2485                 if (endhead.bottomDL)
2486                         os << "\\hline\n";
2487                 os << "\\endhead\n";
2488         }
2489         // output footer info
2490         if (haveLTFoot()) {
2491                 if (endfoot.topDL)
2492                         os << "\\hline\n";
2493                 for (row_type r = 0; r < nrows(); ++r) {
2494                         if (row_info[r].endfoot)
2495                                 TeXRow(os, r, runparams);
2496                 }
2497                 if (endfoot.bottomDL)
2498                         os << "\\hline\n";
2499                 os << "\\endfoot\n";
2500                 if (endlastfoot.empty && !haveLTLastFoot())
2501                         os << "\\endlastfoot\n";
2502         }
2503         // output lastfooter info
2504         if (haveLTLastFoot()) {
2505                 if (endlastfoot.topDL)
2506                         os << "\\hline\n";
2507                 for (row_type r = 0; r < nrows(); ++r) {
2508                         if (row_info[r].endlastfoot)
2509                                 TeXRow(os, r, runparams);
2510                 }
2511                 if (endlastfoot.bottomDL)
2512                         os << "\\hline\n";
2513                 os << "\\endlastfoot\n";
2514         }
2515 }
2516
2517
2518 bool Tabular::isValidRow(row_type row) const
2519 {
2520         if (!is_long_tabular)
2521                 return true;
2522         return !row_info[row].endhead && !row_info[row].endfirsthead
2523                 && !row_info[row].endfoot && !row_info[row].endlastfoot
2524                 && !row_info[row].caption;
2525 }
2526
2527
2528 void Tabular::TeXRow(otexstream & os, row_type row,
2529                      OutputParams const & runparams) const
2530 {
2531         idx_type cell = cellIndex(row, 0);
2532         shared_ptr<InsetTableCell> inset = cellInset(cell);
2533         Paragraph const & par = inset->paragraphs().front();
2534         string const lang = par.getParLanguage(buffer().params())->lang();
2535
2536         //output the top line
2537         TeXTopHLine(os, row, lang);
2538
2539         if (row_info[row].top_space_default) {
2540                 if (use_booktabs)
2541                         os << "\\addlinespace\n";
2542                 else
2543                         os << "\\noalign{\\vskip\\doublerulesep}\n";
2544         } else if(!row_info[row].top_space.zero()) {
2545                 if (use_booktabs)
2546                         os << "\\addlinespace["
2547                            << from_ascii(row_info[row].top_space.asLatexString())
2548                            << "]\n";
2549                 else {
2550                         os << "\\noalign{\\vskip"
2551                            << from_ascii(row_info[row].top_space.asLatexString())
2552                            << "}\n";
2553                 }
2554         }
2555         bool ismulticol = false;
2556         bool ismultirow = false;
2557         for (col_type c = 0; c < ncols(); ++c) {
2558                 if (isPartOfMultiColumn(row, c))
2559                         continue;
2560
2561                 cell = cellIndex(row, c);
2562
2563                 if (isPartOfMultiRow(row, c)
2564                     && column_info[c].alignment != LYX_ALIGN_DECIMAL) {
2565                         if (cell != getLastCellInRow(row))
2566                                 os << " & "; 
2567                         continue;
2568                 }
2569
2570                 TeXCellPreamble(os, cell, ismulticol, ismultirow);
2571                 shared_ptr<InsetTableCell> inset = cellInset(cell);
2572
2573                 Paragraph const & par = inset->paragraphs().front();
2574                 bool rtl = par.isRTL(buffer().params())
2575                         && !par.empty()
2576                         && getPWidth(cell).zero()
2577                         && !runparams.use_polyglossia;
2578
2579                 if (rtl) {
2580                         string const lang =
2581                                 par.getParLanguage(buffer().params())->lang();
2582                         if (lang == "farsi")
2583                                 os << "\\textFR{";
2584                         else if (lang == "arabic_arabi")
2585                                 os << "\\textAR{";
2586                         // currently, remaining RTL languages are
2587                         // arabic_arabtex and hebrew
2588                         else
2589                                 os << "\\R{";
2590                 }
2591                 // pass to the OutputParams that we are in a cell and
2592                 // which alignment we have set.
2593                 // InsetNewline needs this context information.
2594                 OutputParams newrp(runparams);
2595                 newrp.inTableCell = (getAlignment(cell) == LYX_ALIGN_BLOCK)
2596                                     ? OutputParams::PLAIN
2597                                     : OutputParams::ALIGNED;
2598
2599                 if (getAlignment(cell) == LYX_ALIGN_DECIMAL) {
2600                         // copy cell and split in 2
2601                         InsetTableCell head = InsetTableCell(*cellInset(cell).get());
2602                         head.setBuffer(buffer());
2603                         DocIterator dit = cellInset(cell)->getText(0)->macrocontextPosition();
2604                         dit.pop_back();
2605                         dit.push_back(CursorSlice(head));
2606                         head.setMacrocontextPositionRecursive(dit);
2607                         bool hassep = false;
2608                         InsetTableCell tail = splitCell(head, column_info[c].decimal_point, hassep);
2609                         head.latex(os, newrp);
2610                         if (hassep) {
2611                                 os << '&';
2612                                 tail.setBuffer(head.buffer());
2613                                 dit.pop_back();
2614                                 dit.push_back(CursorSlice(tail));
2615                                 tail.setMacrocontextPositionRecursive(dit);
2616                                 tail.latex(os, newrp);
2617                         }
2618                 } else if (!isPartOfMultiRow(row, c)) {
2619                         if (!runparams.nice)
2620                                 os.texrow().start(par.id(), 0);
2621                         inset->latex(os, newrp);
2622                 }
2623
2624                 runparams.encoding = newrp.encoding;
2625                 if (rtl)
2626                         os << '}';
2627
2628                 TeXCellPostamble(os, cell, ismulticol, ismultirow);
2629                 if (cell != getLastCellInRow(row)) { // not last cell in row
2630                         if (runparams.nice)
2631                                 os << " & ";
2632                         else
2633                                 os << " &\n";
2634                 }
2635         }
2636         os << "\\tabularnewline";
2637         if (row_info[row].bottom_space_default) {
2638                 if (use_booktabs)
2639                         os << "\\addlinespace";
2640                 else
2641                         os << "[\\doublerulesep]";
2642         } else if (!row_info[row].bottom_space.zero()) {
2643                 if (use_booktabs)
2644                         os << "\\addlinespace";
2645                 os << '['
2646                    << from_ascii(row_info[row].bottom_space.asLatexString())
2647                    << ']';
2648         }
2649         os << '\n';
2650
2651         //output the bottom line
2652         TeXBottomHLine(os, row, lang);
2653
2654         if (row_info[row].interline_space_default) {
2655                 if (use_booktabs)
2656                         os << "\\addlinespace\n";
2657                 else
2658                         os << "\\noalign{\\vskip\\doublerulesep}\n";
2659         } else if (!row_info[row].interline_space.zero()) {
2660                 if (use_booktabs)
2661                         os << "\\addlinespace["
2662                            << from_ascii(row_info[row].interline_space.asLatexString())
2663                            << "]\n";
2664                 else
2665                         os << "\\noalign{\\vskip"
2666                            << from_ascii(row_info[row].interline_space.asLatexString())
2667                            << "}\n";
2668         }
2669 }
2670
2671
2672 void Tabular::latex(otexstream & os, OutputParams const & runparams) const
2673 {
2674         bool const is_tabular_star = !tabular_width.zero();
2675
2676         //+---------------------------------------------------------------------
2677         //+                      first the opening preamble                    +
2678         //+---------------------------------------------------------------------
2679
2680         os << safebreakln;
2681         if (runparams.lastid != -1)
2682                 os.texrow().start(runparams.lastid, runparams.lastpos);
2683
2684         if (rotate != 0)
2685                 os << "\\begin{turn}{" << convert<string>(rotate) << "}\n";
2686
2687         if (is_long_tabular) {
2688                 os << "\\begin{longtable}";
2689                 switch (longtabular_alignment) {
2690                 case LYX_LONGTABULAR_ALIGN_LEFT:
2691                         os << "[l]";
2692                         break;
2693                 case LYX_LONGTABULAR_ALIGN_CENTER:
2694                         break;
2695                 case LYX_LONGTABULAR_ALIGN_RIGHT:
2696                         os << "[r]";
2697                         break;
2698                 }
2699         } else {
2700                 if (is_tabular_star)
2701                         os << "\\begin{tabular*}{" << from_ascii(tabular_width.asLatexString()) << "}";
2702                 else
2703                         os << "\\begin{tabular}";
2704                 switch (tabular_valignment) {
2705                 case LYX_VALIGN_TOP:
2706                         os << "[t]";
2707                         break;
2708                 case LYX_VALIGN_MIDDLE:
2709                         break;
2710                 case LYX_VALIGN_BOTTOM:
2711                         os << "[b]";
2712                         break;
2713                 }
2714         }
2715         
2716         os << "{";
2717
2718         if (is_tabular_star)
2719                 os << "@{\\extracolsep{\\fill}}";
2720
2721         for (col_type c = 0; c < ncols(); ++c) {
2722                 if (columnLeftLine(c))
2723                         os << '|';
2724                 if (!column_info[c].align_special.empty()) {
2725                         os << column_info[c].align_special;
2726                 } else {
2727                         if (!column_info[c].p_width.zero()) {
2728                                 switch (column_info[c].alignment) {
2729                                 case LYX_ALIGN_LEFT:
2730                                         os << ">{\\raggedright}";
2731                                         break;
2732                                 case LYX_ALIGN_RIGHT:
2733                                         os << ">{\\raggedleft}";
2734                                         break;
2735                                 case LYX_ALIGN_CENTER:
2736                                         os << ">{\\centering}";
2737                                         break;
2738                                 case LYX_ALIGN_NONE:
2739                                 case LYX_ALIGN_BLOCK:
2740                                 case LYX_ALIGN_LAYOUT:
2741                                 case LYX_ALIGN_SPECIAL:
2742                                 case LYX_ALIGN_DECIMAL:
2743                                         break;
2744                                 }
2745
2746                                 switch (column_info[c].valignment) {
2747                                 case LYX_VALIGN_TOP:
2748                                         os << 'p';
2749                                         break;
2750                                 case LYX_VALIGN_MIDDLE:
2751                                         os << 'm';
2752                                         break;
2753                                 case LYX_VALIGN_BOTTOM:
2754                                         os << 'b';
2755                                         break;
2756                         }
2757                                 os << '{'
2758                                    << from_ascii(column_info[c].p_width.asLatexString())
2759                                    << '}';
2760                         } else {
2761                                 switch (column_info[c].alignment) {
2762                                 case LYX_ALIGN_LEFT:
2763                                         os << 'l';
2764                                         break;
2765                                 case LYX_ALIGN_RIGHT:
2766                                         os << 'r';
2767                                         break;
2768                                 case LYX_ALIGN_DECIMAL:
2769                                         os << "r@{\\extracolsep{0pt}" << column_info[c].decimal_point << "}l";
2770                                         break;
2771                                 default:
2772                                         os << 'c';
2773                                         break;
2774                                 }
2775                         } // end if else !column_info[i].p_width
2776                 } // end if else !column_info[i].align_special
2777                 if (columnRightLine(c))
2778                         os << '|';
2779         }
2780         os << "}\n";
2781
2782         TeXLongtableHeaderFooter(os, runparams);
2783
2784         //+---------------------------------------------------------------------
2785         //+                      the single row and columns (cells)            +
2786         //+---------------------------------------------------------------------
2787
2788         for (row_type r = 0; r < nrows(); ++r) {
2789                 if (isValidRow(r)) {
2790                         TeXRow(os, r, runparams);
2791                         if (is_long_tabular && row_info[r].newpage)
2792                                 os << "\\newpage\n";
2793                 }
2794         }
2795
2796         //+---------------------------------------------------------------------
2797         //+                      the closing of the tabular                    +
2798         //+---------------------------------------------------------------------
2799
2800         if (is_long_tabular)
2801                 os << "\\end{longtable}";
2802         else {
2803                 if (is_tabular_star)
2804                         os << "\\end{tabular*}";
2805                 else
2806                         os << "\\end{tabular}";
2807         }
2808
2809         if (rotate != 0)
2810                 os << breakln << "\\end{turn}";
2811 }
2812
2813
2814 int Tabular::docbookRow(odocstream & os, row_type row,
2815                            OutputParams const & runparams) const
2816 {
2817         int ret = 0;
2818         idx_type cell = getFirstCellInRow(row);
2819
2820         os << "<row>\n";
2821         for (col_type c = 0; c < ncols(); ++c) {
2822                 if (isPartOfMultiColumn(row, c))
2823                         continue;
2824
2825                 os << "<entry align=\"";
2826                 switch (getAlignment(cell)) {
2827                 case LYX_ALIGN_LEFT:
2828                         os << "left";
2829                         break;
2830                 case LYX_ALIGN_RIGHT:
2831                         os << "right";
2832                         break;
2833                 default:
2834                         os << "center";
2835                         break;
2836                 }
2837
2838                 os << "\" valign=\"";
2839                 switch (getVAlignment(cell)) {
2840                 case LYX_VALIGN_TOP:
2841                         os << "top";
2842                         break;
2843                 case LYX_VALIGN_BOTTOM:
2844                         os << "bottom";
2845                         break;
2846                 case LYX_VALIGN_MIDDLE:
2847                         os << "middle";
2848                 }
2849                 os << '"';
2850
2851                 if (isMultiColumn(cell)) {
2852                         os << " namest=\"col" << c << "\" ";
2853                         os << "nameend=\"col" << c + columnSpan(cell) - 1 << '"';
2854                 }
2855
2856                 os << '>';
2857                 ret += cellInset(cell)->docbook(os, runparams);
2858                 os << "</entry>\n";
2859                 ++cell;
2860         }
2861         os << "</row>\n";
2862         return ret;
2863 }
2864
2865
2866 int Tabular::docbook(odocstream & os, OutputParams const & runparams) const
2867 {
2868         int ret = 0;
2869
2870         //+---------------------------------------------------------------------
2871         //+                      first the opening preamble                    +
2872         //+---------------------------------------------------------------------
2873
2874         os << "<tgroup cols=\"" << ncols()
2875            << "\" colsep=\"1\" rowsep=\"1\">\n";
2876
2877         for (col_type c = 0; c < ncols(); ++c) {
2878                 os << "<colspec colname=\"col" << c << "\" align=\"";
2879                 switch (column_info[c].alignment) {
2880                 case LYX_ALIGN_LEFT:
2881                         os << "left";
2882                         break;
2883                 case LYX_ALIGN_RIGHT:
2884                         os << "right";
2885                         break;
2886                 default:
2887                         os << "center";
2888                         break;
2889                 }
2890                 os << '"';
2891                 if (runparams.flavor == OutputParams::XML)
2892                         os << '/';
2893                 os << ">\n";
2894                 ++ret;
2895         }
2896
2897         //+---------------------------------------------------------------------
2898         //+                      Long Tabular case                             +
2899         //+---------------------------------------------------------------------
2900
2901         // output caption info
2902         // The caption flag wins over head/foot
2903         if (haveLTCaption()) {
2904                 os << "<caption>\n";
2905                 ++ret;
2906                 for (row_type r = 0; r < nrows(); ++r) {
2907                         if (row_info[r].caption) {
2908                                 ret += docbookRow(os, r, runparams);
2909                         }
2910                 }
2911                 os << "</caption>\n";
2912                 ++ret;
2913         }
2914         // output header info
2915         if (haveLTHead(false) || haveLTFirstHead(false)) {
2916                 os << "<thead>\n";
2917                 ++ret;
2918                 for (row_type r = 0; r < nrows(); ++r) {
2919                         if ((row_info[r].endhead || row_info[r].endfirsthead) &&
2920                             !row_info[r].caption) {
2921                                 ret += docbookRow(os, r, runparams);
2922                         }
2923                 }
2924                 os << "</thead>\n";
2925                 ++ret;
2926         }
2927         // output footer info
2928         if (haveLTFoot(false) || haveLTLastFoot(false)) {
2929                 os << "<tfoot>\n";
2930                 ++ret;
2931                 for (row_type r = 0; r < nrows(); ++r) {
2932                         if ((row_info[r].endfoot || row_info[r].endlastfoot) &&
2933                             !row_info[r].caption) {
2934                                 ret += docbookRow(os, r, runparams);
2935                         }
2936                 }
2937                 os << "</tfoot>\n";
2938                 ++ret;
2939         }
2940
2941         //+---------------------------------------------------------------------
2942         //+                      the single row and columns (cells)            +
2943         //+---------------------------------------------------------------------
2944
2945         os << "<tbody>\n";
2946         ++ret;
2947         for (row_type r = 0; r < nrows(); ++r) {
2948                 if (isValidRow(r)) {
2949                         ret += docbookRow(os, r, runparams);
2950                 }
2951         }
2952         os << "</tbody>\n";
2953         ++ret;
2954         //+---------------------------------------------------------------------
2955         //+                      the closing of the tabular                    +
2956         //+---------------------------------------------------------------------
2957
2958         os << "</tgroup>";
2959         ++ret;
2960
2961         return ret;
2962 }
2963
2964
2965 docstring Tabular::xhtmlRow(XHTMLStream & xs, row_type row,
2966                            OutputParams const & runparams, bool header) const
2967 {
2968         docstring ret;
2969         string const celltag = header ? "th" : "td";
2970         idx_type cell = getFirstCellInRow(row);
2971
2972         xs << html::StartTag("tr");
2973         for (col_type c = 0; c < ncols(); ++c) {
2974                 if (isPartOfMultiColumn(row, c) || isPartOfMultiRow(row, c))
2975                         continue;
2976
2977                 stringstream attr;
2978                 attr << "align='";
2979                 switch (getAlignment(cell)) {
2980                 case LYX_ALIGN_LEFT:
2981                         attr << "left";
2982                         break;
2983                 case LYX_ALIGN_RIGHT:
2984                         attr << "right";
2985                         break;
2986                 default:
2987                         attr << "center";
2988                         break;
2989                 }
2990                 attr << "'";
2991                 attr << " valign='";
2992                 switch (getVAlignment(cell)) {
2993                 case LYX_VALIGN_TOP:
2994                         attr << "top";
2995                         break;
2996                 case LYX_VALIGN_BOTTOM:
2997                         attr << "bottom";
2998                         break;
2999                 case LYX_VALIGN_MIDDLE:
3000                         attr << "middle";
3001                 }
3002                 attr << "'";
3003
3004                 if (isMultiColumn(cell))
3005                         attr << " colspan='" << columnSpan(cell) << "'";
3006                 else if (isMultiRow(cell))
3007                         attr << " rowspan='" << rowSpan(cell) << "'";
3008
3009                 xs << html::StartTag(celltag, attr.str()) << html::CR();
3010                 ret += cellInset(cell)->xhtml(xs, runparams);
3011                 xs << html::EndTag(celltag) << html::CR();
3012                 ++cell;
3013         }
3014         xs << html::EndTag("tr");
3015         return ret;
3016 }
3017
3018
3019 docstring Tabular::xhtml(XHTMLStream & xs, OutputParams const & runparams) const
3020 {
3021         docstring ret;
3022
3023         if (is_long_tabular) {
3024                 // we'll wrap it in a div, so as to deal with alignment
3025                 string align;
3026                 switch (longtabular_alignment) {
3027                 case LYX_LONGTABULAR_ALIGN_LEFT:
3028                         align = "left";
3029                         break;
3030                 case LYX_LONGTABULAR_ALIGN_CENTER:
3031                         align = "center";
3032                         break;
3033                 case LYX_LONGTABULAR_ALIGN_RIGHT:
3034                         align = "right";
3035                         break;
3036                 }
3037                 xs << html::StartTag("div", "class='longtable' style='text-align: " + align + ";'")
3038                    << html::CR();
3039                 // The caption flag wins over head/foot
3040                 if (haveLTCaption()) {
3041                         xs << html::StartTag("div", "class='longtable-caption' style='text-align: " + align + ";'")
3042                            << html::CR();
3043                         for (row_type r = 0; r < nrows(); ++r)
3044                                 if (row_info[r].caption)
3045                                         ret += xhtmlRow(xs, r, runparams);
3046                         xs << html::EndTag("div") << html::CR();
3047                 }
3048         }
3049
3050         xs << html::StartTag("table") << html::CR();
3051
3052         // output header info
3053         bool const havefirsthead = haveLTFirstHead(false);
3054         // if we have a first head, then we are going to ignore the
3055         // headers for the additional pages, since there aren't any
3056         // in XHTML. this test accomplishes that.
3057         bool const havehead = !havefirsthead && haveLTHead(false);
3058         if (havehead || havefirsthead) {
3059                 xs << html::StartTag("thead") << html::CR();
3060                 for (row_type r = 0; r < nrows(); ++r) {
3061                         if (((havefirsthead && row_info[r].endfirsthead) ||
3062                              (havehead && row_info[r].endhead)) &&
3063                             !row_info[r].caption) {
3064                                 ret += xhtmlRow(xs, r, runparams, true);
3065                         }
3066                 }
3067                 xs << html::EndTag("thead") << html::CR();
3068         }
3069         // output footer info
3070         bool const havelastfoot = haveLTLastFoot(false);
3071         // as before.
3072         bool const havefoot = !havelastfoot && haveLTFoot(false);
3073         if (havefoot || havelastfoot) {
3074                 xs << html::StartTag("tfoot") << html::CR();
3075                 for (row_type r = 0; r < nrows(); ++r) {
3076                         if (((havelastfoot && row_info[r].endlastfoot) ||
3077                              (havefoot && row_info[r].endfoot)) &&
3078                             !row_info[r].caption) {
3079                                 ret += xhtmlRow(xs, r, runparams);
3080                         }
3081                 }
3082                 xs << html::EndTag("tfoot") << html::CR();
3083         }
3084
3085         xs << html::StartTag("tbody") << html::CR();
3086         for (row_type r = 0; r < nrows(); ++r) {
3087                 if (isValidRow(r)) {
3088                         ret += xhtmlRow(xs, r, runparams);
3089                 }
3090         }
3091         xs << html::EndTag("tbody")
3092            << html::CR()
3093            << html::EndTag("table")
3094            << html::CR();
3095         if (is_long_tabular)
3096                 xs << html::EndTag("div") << html::CR();
3097         return ret;
3098 }
3099
3100
3101 bool Tabular::plaintextTopHLine(odocstringstream & os, row_type row,
3102                                    vector<unsigned int> const & clen) const
3103 {
3104         idx_type const fcell = getFirstCellInRow(row);
3105         idx_type const n = numberOfCellsInRow(row) + fcell;
3106         idx_type tmp = 0;
3107
3108         for (idx_type i = fcell; i < n; ++i) {
3109                 if (topLine(i)) {
3110                         ++tmp;
3111                         break;
3112                 }
3113         }
3114         if (!tmp)
3115                 return false;
3116
3117         char_type ch;
3118         for (idx_type i = fcell; i < n; ++i) {
3119                 if (topLine(i)) {
3120                         if (leftLine(i))
3121                                 os << "+-";
3122                         else
3123                                 os << "--";
3124                         ch = '-';
3125                 } else {
3126                         os << "  ";
3127                         ch = ' ';
3128                 }
3129                 col_type column = cellColumn(i);
3130                 int len = clen[column];
3131                 while (column < ncols() - 1
3132                        && isPartOfMultiColumn(row, ++column))
3133                         len += clen[column] + 4;
3134                 os << docstring(len, ch);
3135                 if (topLine(i)) {
3136                         if (rightLine(i))
3137                                 os << "-+";
3138                         else
3139                                 os << "--";
3140                 } else {
3141                         os << "  ";
3142                 }
3143         }
3144         os << endl;
3145         return true;
3146 }
3147
3148
3149 bool Tabular::plaintextBottomHLine(odocstringstream & os, row_type row,
3150                                       vector<unsigned int> const & clen) const
3151 {
3152         idx_type const fcell = getFirstCellInRow(row);
3153         idx_type const n = numberOfCellsInRow(row) + fcell;
3154         idx_type tmp = 0;
3155
3156         for (idx_type i = fcell; i < n; ++i) {
3157                 if (bottomLine(i)) {
3158                         ++tmp;
3159                         break;
3160                 }
3161         }
3162         if (!tmp)
3163                 return false;
3164
3165         char_type ch;
3166         for (idx_type i = fcell; i < n; ++i) {
3167                 if (bottomLine(i)) {
3168                         if (leftLine(i))
3169                                 os << "+-";
3170                         else
3171                                 os << "--";
3172                         ch = '-';
3173                 } else {
3174                         os << "  ";
3175                         ch = ' ';
3176                 }
3177                 col_type column = cellColumn(i);
3178                 int len = clen[column];
3179                 while (column < ncols() - 1 && isPartOfMultiColumn(row, ++column))
3180                         len += clen[column] + 4;
3181                 os << docstring(len, ch);
3182                 if (bottomLine(i)) {
3183                         if (rightLine(i))
3184                                 os << "-+";
3185                         else
3186                                 os << "--";
3187                 } else {
3188                         os << "  ";
3189                 }
3190         }
3191         os << endl;
3192         return true;
3193 }
3194
3195
3196 void Tabular::plaintextPrintCell(odocstringstream & os,
3197                                OutputParams const & runparams,
3198                                idx_type cell, row_type row, col_type column,
3199                                vector<unsigned int> const & clen,
3200                                bool onlydata, size_t max_length) const
3201 {
3202         odocstringstream sstr;
3203         cellInset(cell)->plaintext(sstr, runparams, max_length);
3204
3205         if (onlydata) {
3206                 os << sstr.str();
3207                 return;
3208         }
3209
3210         if (leftLine(cell))
3211                 os << "| ";
3212         else
3213                 os << "  ";
3214
3215         unsigned int len1 = sstr.str().length();
3216         unsigned int len2 = clen[column];
3217         while (column < ncols() - 1 && isPartOfMultiColumn(row, ++column))
3218                 len2 += clen[column] + 4;
3219         len2 -= len1;
3220
3221         switch (getAlignment(cell)) {
3222         default:
3223         case LYX_ALIGN_LEFT:
3224                 len1 = 0;
3225                 break;
3226         case LYX_ALIGN_RIGHT:
3227                 len1 = len2;
3228                 len2 = 0;
3229                 break;
3230         case LYX_ALIGN_CENTER:
3231                 len1 = len2 / 2;
3232                 len2 -= len1;
3233                 break;
3234         }
3235
3236         os << docstring(len1, ' ') << sstr.str()
3237            << docstring(len2, ' ');
3238
3239         if (rightLine(cell))
3240                 os << " |";
3241         else
3242                 os << "  ";
3243 }
3244
3245
3246 void Tabular::plaintext(odocstringstream & os,
3247                            OutputParams const & runparams, int const depth,
3248                            bool onlydata, char_type delim, size_t max_length) const
3249 {
3250         // first calculate the width of the single columns
3251         vector<unsigned int> clen(ncols());
3252
3253         if (!onlydata) {
3254                 // first all non multicolumn cells!
3255                 for (col_type c = 0; c < ncols(); ++c) {
3256                         clen[c] = 0;
3257                         for (row_type r = 0; r < nrows(); ++r) {
3258                                 idx_type cell = cellIndex(r, c);
3259                                 if (isMultiColumn(cell))
3260                                         continue;
3261                                 odocstringstream sstr;
3262                                 cellInset(cell)->plaintext(sstr, runparams, max_length);
3263                                 if (clen[c] < sstr.str().length())
3264                                         clen[c] = sstr.str().length();
3265                         }
3266                 }
3267                 // then all multicolumn cells!
3268                 for (col_type c = 0; c < ncols(); ++c) {
3269                         for (row_type r = 0; r < nrows(); ++r) {
3270                                 idx_type cell = cellIndex(r, c);
3271                                 if (cell_info[r][c].multicolumn != CELL_BEGIN_OF_MULTICOLUMN)
3272                                         continue;
3273                                 odocstringstream sstr;
3274                                 cellInset(cell)->plaintext(sstr, runparams, max_length);
3275                                 int len = int(sstr.str().length());
3276                                 idx_type const n = columnSpan(cell);
3277                                 for (col_type k = c; len > 0 && k < c + n - 1; ++k)
3278                                         len -= clen[k];
3279                                 if (len > int(clen[c + n - 1]))
3280                                         clen[c + n - 1] = len;
3281                         }
3282                 }
3283         }
3284         idx_type cell = 0;
3285         for (row_type r = 0; r < nrows(); ++r) {
3286                 if (!onlydata && plaintextTopHLine(os, r, clen))
3287                         os << docstring(depth * 2, ' ');
3288                 for (col_type c = 0; c < ncols(); ++c) {
3289                         if (isPartOfMultiColumn(r, c) || isPartOfMultiRow(r,c))
3290                                 continue;
3291                         if (onlydata && c > 0)
3292                                 // we don't use operator<< for single UCS4 character.
3293                                 // see explanation in docstream.h
3294                                 os.put(delim);
3295                         plaintextPrintCell(os, runparams, cell, r, c, clen, onlydata, max_length);
3296                         ++cell;
3297                         if (os.str().size() > max_length)
3298                                 break;
3299                 }
3300                 os << endl;
3301                 if (!onlydata) {
3302                         os << docstring(depth * 2, ' ');
3303                         if (plaintextBottomHLine(os, r, clen))
3304                                 os << docstring(depth * 2, ' ');
3305                 }
3306                 if (os.str().size() > max_length)
3307                         break;
3308         }
3309 }
3310
3311
3312 shared_ptr<InsetTableCell> Tabular::cellInset(idx_type cell) const
3313 {
3314         return cell_info[cellRow(cell)][cellColumn(cell)].inset;
3315 }
3316
3317
3318 shared_ptr<InsetTableCell> Tabular::cellInset(row_type row,
3319                                                col_type column) const
3320 {
3321         return cell_info[row][column].inset;
3322 }
3323
3324
3325 void Tabular::setCellInset(row_type row, col_type column,
3326                               shared_ptr<InsetTableCell> ins) const
3327 {
3328         CellData & cd = cell_info[row][column];
3329         cd.inset = ins;
3330 }
3331
3332
3333 void Tabular::validate(LaTeXFeatures & features) const
3334 {
3335         features.require("NeedTabularnewline");
3336         if (use_booktabs)
3337                 features.require("booktabs");
3338         if (is_long_tabular)
3339                 features.require("longtable");
3340         if (needRotating())
3341                 features.require("rotating");
3342         for (idx_type cell = 0; cell < numberofcells; ++cell) {
3343                 if (isMultiRow(cell))
3344                         features.require("multirow");
3345                 if (getVAlignment(cell) != LYX_VALIGN_TOP
3346                     || !getPWidth(cell).zero())
3347                         features.require("array");
3348                 cellInset(cell)->validate(features);
3349         }
3350 }
3351
3352
3353 Tabular::BoxType Tabular::useParbox(idx_type cell) const
3354 {
3355         ParagraphList const & parlist = cellInset(cell)->paragraphs();
3356         ParagraphList::const_iterator cit = parlist.begin();
3357         ParagraphList::const_iterator end = parlist.end();
3358
3359         for (; cit != end; ++cit)
3360                 for (int i = 0; i < cit->size(); ++i)
3361                         if (cit->isNewline(i))
3362                                 return BOX_PARBOX;
3363
3364         return BOX_NONE;
3365 }
3366
3367
3368 /////////////////////////////////////////////////////////////////////
3369 //
3370 // InsetTableCell
3371 //
3372 /////////////////////////////////////////////////////////////////////
3373
3374 InsetTableCell::InsetTableCell(Buffer * buf)
3375         : InsetText(buf, InsetText::PlainLayout), isFixedWidth(false),
3376           contentAlign(LYX_ALIGN_CENTER)
3377 {}
3378
3379
3380 bool InsetTableCell::forcePlainLayout(idx_type) const
3381 {
3382         return !isFixedWidth;
3383 }
3384
3385
3386 bool InsetTableCell::allowParagraphCustomization(idx_type) const
3387 {
3388         return isFixedWidth;
3389 }
3390
3391
3392 bool InsetTableCell::getStatus(Cursor & cur, FuncRequest const & cmd,
3393         FuncStatus & status) const
3394 {
3395         bool enabled = true;
3396         switch (cmd.action()) {
3397         case LFUN_LAYOUT:
3398                 enabled = !forcePlainLayout();
3399                 break;
3400         case LFUN_LAYOUT_PARAGRAPH:
3401                 enabled = allowParagraphCustomization();
3402                 break;
3403
3404         case LFUN_MATH_DISPLAY:
3405                 if (!hasFixedWidth()) {
3406                         enabled = false;
3407                         break;
3408                 } //fall-through
3409         default:
3410                 return InsetText::getStatus(cur, cmd, status);
3411         }
3412         status.setEnabled(enabled);
3413         return true;
3414 }
3415
3416 docstring InsetTableCell::asString(bool intoInsets) 
3417 {
3418         docstring retval;
3419         if (paragraphs().empty())
3420                 return retval;
3421         ParagraphList::const_iterator it = paragraphs().begin();
3422         ParagraphList::const_iterator en = paragraphs().end();
3423         bool first = true;
3424         for (; it != en; ++it) {
3425                 if (!first)
3426                         retval += "\n";
3427                 else
3428                         first = false;
3429                 retval += it->asString(intoInsets ? AS_STR_INSETS : AS_STR_NONE);
3430         }
3431         return retval;
3432 }
3433
3434
3435 void InsetTableCell::addToToc(DocIterator const & di, bool output_active) const
3436 {
3437         InsetText::iterateForToc(di, output_active);
3438 }
3439
3440
3441 docstring InsetTableCell::xhtml(XHTMLStream & xs, OutputParams const & rp) const
3442 {
3443         if (!isFixedWidth)
3444                 return InsetText::insetAsXHTML(xs, rp, InsetText::JustText);
3445         return InsetText::xhtml(xs, rp);
3446 }
3447
3448
3449
3450 /////////////////////////////////////////////////////////////////////
3451 //
3452 // InsetTabular
3453 //
3454 /////////////////////////////////////////////////////////////////////
3455
3456 InsetTabular::InsetTabular(Buffer * buf, row_type rows,
3457                            col_type columns)
3458         : Inset(buf), tabular(buf, max(rows, row_type(1)), max(columns, col_type(1))), scx_(0), 
3459         rowselect_(false), colselect_(false)
3460 {
3461 }
3462
3463
3464 InsetTabular::InsetTabular(InsetTabular const & tab)
3465         : Inset(tab), tabular(tab.tabular),  scx_(0)
3466 {
3467 }
3468
3469
3470 InsetTabular::~InsetTabular()
3471 {
3472         hideDialogs("tabular", this);
3473 }
3474
3475
3476 void InsetTabular::setBuffer(Buffer & buf)
3477 {
3478         tabular.setBuffer(buf);
3479         Inset::setBuffer(buf);
3480 }
3481
3482
3483 bool InsetTabular::insetAllowed(InsetCode code) const
3484 {
3485         switch (code) {
3486         case FLOAT_CODE:
3487         case MARGIN_CODE:
3488         case MATHMACRO_CODE:
3489         case WRAP_CODE:
3490                 return false;
3491
3492         case CAPTION_CODE:
3493                 return tabular.is_long_tabular;
3494
3495         default:
3496                 return true;
3497         }
3498 }
3499
3500
3501 bool InsetTabular::allowsCaptionVariation(std::string const & newtype) const
3502 {
3503         return tabular.is_long_tabular &&
3504                 (newtype == "Standard" || newtype == "LongTableNoNumber");
3505 }
3506
3507
3508 void InsetTabular::write(ostream & os) const
3509 {
3510         os << "Tabular" << endl;
3511         tabular.write(os);
3512 }
3513
3514
3515 string InsetTabular::contextMenu(BufferView const &, int, int) const
3516 {
3517         // FIXME: depending on the selection state,
3518         // we could offer a different menu.
3519         return cell(0)->contextMenuName() + ";" + contextMenuName();
3520 }
3521
3522
3523 string InsetTabular::contextMenuName() const
3524 {
3525         return "context-tabular";
3526 }
3527
3528
3529 void InsetTabular::read(Lexer & lex)
3530 {
3531         //bool const old_format = (lex.getString() == "\\LyXTable");
3532
3533         tabular.read(lex);
3534
3535         //if (old_format)
3536         //      return;
3537
3538         lex.next();
3539         string token = lex.getString();
3540         while (lex && token != "\\end_inset") {
3541                 lex.next();
3542                 token = lex.getString();
3543         }
3544         if (!lex)
3545                 lex.printError("Missing \\end_inset at this point. ");
3546 }
3547
3548
3549 int InsetTabular::rowFromY(Cursor & cur, int y) const
3550 {
3551         // top y coordinate of tabular
3552         int h = yo(cur.bv()) - tabular.rowAscent(0) + offset_valign_;
3553         row_type r = 0;
3554         for (; r < tabular.nrows() && y > h; ++r)
3555                 h += tabular.rowAscent(r) + tabular.rowDescent(r)
3556                         + tabular.interRowSpace(r);
3557
3558         return r - 1;
3559 }
3560
3561
3562 int InsetTabular::columnFromX(Cursor & cur, int x) const
3563 {
3564         // left x coordinate of tabular
3565         int w = xo(cur.bv()) + ADD_TO_TABULAR_WIDTH;
3566         col_type c = 0;
3567         for (; c < tabular.ncols() && x > w; ++c)
3568                 w += tabular.cellWidth(c);
3569         return c - 1;
3570 }
3571
3572
3573 void InsetTabular::metrics(MetricsInfo & mi, Dimension & dim) const
3574 {
3575         //lyxerr << "InsetTabular::metrics: " << mi.base.bv << " width: " <<
3576         //      mi.base.textwidth << "\n";
3577         LBUFERR(mi.base.bv);
3578
3579         for (row_type r = 0; r < tabular.nrows(); ++r) {
3580                 int maxasc = 0;
3581                 int maxdes = 0;
3582                 for (col_type c = 0; c < tabular.ncols(); ++c) {
3583                         if (tabular.isPartOfMultiColumn(r, c)
3584                                 || tabular.isPartOfMultiRow(r, c))
3585                                 // multicolumn or multirow cell, but not first one
3586                                 continue;
3587                         idx_type const cell = tabular.cellIndex(r, c);
3588                         Dimension dim;
3589                         MetricsInfo m = mi;
3590                         Length const p_width = tabular.getPWidth(cell);
3591                         if (!p_width.zero())
3592                                 m.base.textwidth = p_width.inPixels(mi.base.textwidth);
3593                         tabular.cellInset(cell)->metrics(m, dim);
3594                         if (!p_width.zero())
3595                                 dim.wid = m.base.textwidth;
3596                         tabular.cellInfo(cell).width = dim.wid + 2 * WIDTH_OF_LINE 
3597                                 + tabular.interColumnSpace(cell);
3598
3599                         // FIXME(?): do we need a second metrics call?
3600                         TextMetrics const & tm = 
3601                                 mi.base.bv->textMetrics(tabular.cellInset(cell)->getText(0));
3602
3603                         // determine horizontal offset because of decimal align (if necessary)
3604                         int decimal_width = 0;
3605                         if (tabular.getAlignment(cell) == LYX_ALIGN_DECIMAL) {
3606                                 InsetTableCell tail = InsetTableCell(*tabular.cellInset(cell).get());
3607                                 tail.setBuffer(tabular.buffer());
3608                                 // we need to set macrocontext position everywhere
3609                                 // otherwise we crash with nested insets (e.g. footnotes)
3610                                 // after decimal point
3611                                 DocIterator dit = tabular.cellInset(cell)->getText(0)->macrocontextPosition();
3612                                 dit.pop_back();
3613                                 dit.push_back(CursorSlice(tail));
3614                                 tail.setMacrocontextPositionRecursive(dit);
3615
3616                                 // remove text leading decimal point
3617                                 docstring const align_d = tabular.column_info[c].decimal_point;
3618                                 dit = separatorPos(&tail, align_d);
3619
3620                                 pit_type const psize = tail.paragraphs().front().size();
3621                                 if (dit) {
3622                                         tail.paragraphs().front().eraseChars(0,
3623                                                 dit.pos() < psize ? dit.pos() + 1 : psize, false);
3624                                         Dimension dim1;
3625                                         tail.metrics(m, dim1);
3626                                         decimal_width = dim1.width();
3627                                 }
3628                         }
3629                         tabular.cell_info[r][c].decimal_hoffset = tm.width() - decimal_width;
3630                         tabular.cell_info[r][c].decimal_width = decimal_width;
3631
3632                         // with LYX_VALIGN_BOTTOM the descent is relative to the last par
3633                         // = descent of text in last par + TEXT_TO_INSET_OFFSET:
3634                         int const lastpardes = tm.last().second->descent()
3635                                 + TEXT_TO_INSET_OFFSET;
3636                         int offset = 0;
3637                         switch (tabular.getVAlignment(cell)) { 
3638                                 case Tabular::LYX_VALIGN_TOP:
3639                                         break; 
3640                                 case Tabular::LYX_VALIGN_MIDDLE:
3641                                         offset = -(dim.des - lastpardes)/2; 
3642                                         break; 
3643                                 case Tabular::LYX_VALIGN_BOTTOM:
3644                                         offset = -(dim.des - lastpardes); 
3645                                         break;
3646                         }
3647                         tabular.cell_info[r][c].voffset = offset;
3648                         maxasc = max(maxasc, dim.asc - offset);
3649                         maxdes = max(maxdes, dim.des + offset);
3650                 }
3651                 int const top_space = tabular.row_info[r].top_space_default ?
3652                         default_line_space :
3653                         tabular.row_info[r].top_space.inPixels(mi.base.textwidth);
3654                 tabular.setRowAscent(r, maxasc + ADD_TO_HEIGHT + top_space);
3655                 int const bottom_space = tabular.row_info[r].bottom_space_default ?
3656                         default_line_space :
3657                         tabular.row_info[r].bottom_space.inPixels(mi.base.textwidth);
3658                 tabular.setRowDescent(r, maxdes + ADD_TO_HEIGHT + bottom_space);
3659         }
3660
3661         // for top-alignment the first horizontal table line must be exactly at
3662         // the position of the base line of the surrounding text line
3663         // for bottom alignment, the same is for the last table line
3664         switch (tabular.tabular_valignment) {
3665         case Tabular::LYX_VALIGN_BOTTOM:
3666                 offset_valign_ = tabular.rowAscent(0) - tabular.height();
3667                 break;
3668         case Tabular::LYX_VALIGN_MIDDLE:
3669                 offset_valign_ = (- tabular.height()) / 2 + tabular.rowAscent(0);
3670                 break;
3671         case Tabular::LYX_VALIGN_TOP:
3672                 offset_valign_ = tabular.rowAscent(0);
3673                 break;
3674         }
3675
3676         tabular.updateColumnWidths();
3677         dim.asc = tabular.rowAscent(0) - offset_valign_;        
3678         dim.des = tabular.height() - dim.asc;
3679         dim.wid = tabular.width() + 2 * ADD_TO_TABULAR_WIDTH;
3680 }
3681
3682
3683 bool InsetTabular::isCellSelected(Cursor & cur, row_type row, col_type col) 
3684         const
3685 {
3686         if (&cur.inset() == this && cur.selection()) {
3687                 if (cur.selIsMultiCell()) {
3688                         row_type rs, re;
3689                         col_type cs, ce;
3690                         getSelection(cur, rs, re, cs, ce);
3691                         
3692                         idx_type const cell = tabular.cellIndex(row, col);
3693                         col_type const cspan = tabular.columnSpan(cell);
3694                         row_type const rspan = tabular.rowSpan(cell);
3695                         if (col + cspan - 1 >= cs && col <= ce 
3696                                 && row + rspan - 1 >= rs && row <= re)
3697                                 return true;
3698                 } else 
3699                         if (col == tabular.cellColumn(cur.idx()) 
3700                                 && row == tabular.cellRow(cur.idx())) {
3701                         CursorSlice const & beg = cur.selBegin();
3702                         CursorSlice const & end = cur.selEnd();
3703
3704                         if ((end.lastpos() > 0 || end.lastpit() > 0)
3705                                   && end.pos() == end.lastpos() && beg.pos() == 0
3706                                   && end.pit() == end.lastpit() && beg.pit() == 0)
3707                                 return true;
3708                 }
3709         }
3710         return false;
3711 }
3712
3713
3714 void InsetTabular::draw(PainterInfo & pi, int x, int y) const
3715 {
3716         x += scx_ + ADD_TO_TABULAR_WIDTH;
3717
3718         BufferView * bv = pi.base.bv;
3719         Cursor & cur = pi.base.bv->cursor();
3720         resetPos(cur);
3721
3722         // FIXME: As the full background is painted in drawBackground(),
3723         // we have no choice but to do a full repaint for the Text cells.
3724         pi.full_repaint = true;
3725
3726         bool const original_selection_state = pi.selected;
3727
3728         idx_type idx = 0;
3729         first_visible_cell = Tabular::npos;
3730
3731         int yy = y + offset_valign_;
3732         for (row_type r = 0; r < tabular.nrows(); ++r) {
3733                 int nx = x;
3734                 for (col_type c = 0; c < tabular.ncols(); ++c) {
3735                         if (tabular.isPartOfMultiColumn(r, c))
3736                                 continue;
3737                         
3738                         idx = tabular.cellIndex(r, c);
3739                         
3740                         if (tabular.isPartOfMultiRow(r, c)) {
3741                                 nx += tabular.cellWidth(idx);
3742                                 continue;
3743                         }
3744
3745                         if (first_visible_cell == Tabular::npos)
3746                                 first_visible_cell = idx;
3747
3748                         pi.selected |= isCellSelected(cur, r, c);
3749                         int const cx = nx + tabular.textHOffset(idx);
3750                         int const cy = yy + tabular.textVOffset(idx);
3751                         // Cache the Inset position.
3752                         bv->coordCache().insets().add(cell(idx).get(), cx, cy);
3753                         cell(idx)->draw(pi, cx, cy);
3754                         drawCellLines(pi, nx, yy, r, idx);
3755                         nx += tabular.cellWidth(idx);
3756                         pi.selected = original_selection_state;
3757                 }
3758
3759                 if (r + 1 < tabular.nrows())
3760                         yy += tabular.rowDescent(r) + tabular.rowAscent(r + 1) 
3761                                 + tabular.interRowSpace(r + 1);
3762         }
3763 }
3764
3765
3766 void InsetTabular::drawBackground(PainterInfo & pi, int x, int y) const
3767 {
3768         x += scx_ + ADD_TO_TABULAR_WIDTH;
3769         y += offset_valign_ - tabular.rowAscent(0);
3770         pi.pain.fillRectangle(x, y, tabular.width(), tabular.height(),
3771                 pi.backgroundColor(this));
3772 }
3773
3774
3775 void InsetTabular::drawSelection(PainterInfo & pi, int x, int y) const
3776 {
3777         Cursor & cur = pi.base.bv->cursor();
3778         resetPos(cur);
3779
3780         x += scx_ + ADD_TO_TABULAR_WIDTH;
3781
3782         if (!cur.selection())
3783                 return;
3784         if (&cur.inset() != this)
3785                 return;
3786
3787         //resetPos(cur);
3788
3789         bool const full_cell_selected = isCellSelected(cur,
3790                 tabular.cellRow(cur.idx()), tabular.cellColumn(cur.idx()));
3791
3792         if (cur.selIsMultiCell() || full_cell_selected) {
3793                 for (row_type r = 0; r < tabular.nrows(); ++r) {
3794                         int xx = x;
3795                         for (col_type c = 0; c < tabular.ncols(); ++c) {
3796                                 if (tabular.isPartOfMultiColumn(r, c))
3797                                         continue;
3798
3799                                 idx_type const cell = tabular.cellIndex(r, c);
3800
3801                                 if (tabular.isPartOfMultiRow(r, c)) {
3802                                         xx += tabular.cellWidth(cell);
3803                                         continue;
3804                                 }
3805                                 int const w = tabular.cellWidth(cell);
3806                                 int const h = tabular.cellHeight(cell);
3807                                 int const yy = y - tabular.rowAscent(r) + offset_valign_;
3808                                 if (isCellSelected(cur, r, c))
3809                                         pi.pain.fillRectangle(xx, yy, w, h, Color_selection);
3810                                 xx += w;
3811                         }
3812                         if (r + 1 < tabular.nrows())
3813                                 y += tabular.rowDescent(r) + tabular.rowAscent(r + 1)
3814                                      + tabular.interRowSpace(r + 1);
3815                 }
3816
3817         } 
3818         // FIXME: This code has no effect because InsetTableCell does not handle
3819         // drawSelection other than the trivial implementation in Inset.
3820         //else {
3821         //      x += cellXPos(cur.idx());
3822         //      x += tabular.textHOffset(cur.idx());
3823         //      cell(cur.idx())->drawSelection(pi, x, 0 /* ignored */);
3824         //}
3825 }
3826
3827
3828 void InsetTabular::drawCellLines(PainterInfo & pi, int x, int y,
3829                                  row_type row, idx_type cell) const
3830 {
3831         y -= tabular.rowAscent(row);
3832         int const w = tabular.cellWidth(cell);
3833         int const h = tabular.cellHeight(cell);
3834         Color const linecolor = pi.textColor(Color_tabularline);
3835         Color const gridcolor = pi.textColor(Color_tabularonoffline);
3836
3837         // Top
3838         bool drawline = tabular.topLine(cell)
3839                 || (row > 0 && tabular.bottomLine(tabular.cellAbove(cell)));
3840         pi.pain.line(x, y, x + w, y,
3841                 drawline ? linecolor : gridcolor,
3842                 drawline ? Painter::line_solid : Painter::line_onoffdash);
3843
3844         // Bottom
3845         drawline = tabular.bottomLine(cell);
3846         pi.pain.line(x, y + h, x + w, y + h,
3847                 drawline ? linecolor : gridcolor,
3848                 drawline ? Painter::line_solid : Painter::line_onoffdash);
3849
3850         // Left
3851         col_type const col = tabular.cellColumn(cell);
3852         drawline = tabular.leftLine(cell)
3853                 || (col > 0 && tabular.rightLine(tabular.cellIndex(row, col - 1)));
3854         pi.pain.line(x, y, x, y + h,
3855                 drawline ? linecolor : gridcolor,
3856                 drawline ? Painter::line_solid : Painter::line_onoffdash);
3857
3858         // Right
3859         x -= tabular.interColumnSpace(cell);
3860         col_type next_cell_col = col + 1;
3861         while (next_cell_col < tabular.ncols() 
3862                 && tabular.isMultiColumn(tabular.cellIndex(row, next_cell_col)))
3863                 next_cell_col++;
3864         drawline = tabular.rightLine(cell)
3865                    || (next_cell_col < tabular.ncols()
3866                        && tabular.leftLine(tabular.cellIndex(row, next_cell_col)));
3867         pi.pain.line(x + w, y, x + w, y + h,
3868                 drawline ? linecolor : gridcolor,
3869                 drawline ? Painter::line_solid : Painter::line_onoffdash);
3870 }
3871
3872
3873 void InsetTabular::edit(Cursor & cur, bool front, EntryDirection)
3874 {
3875         //lyxerr << "InsetTabular::edit: " << this << endl;
3876         cur.finishUndo();
3877         cur.setSelection(false);
3878         cur.push(*this);
3879         if (front) {
3880                 if (isRightToLeft(cur))
3881                         cur.idx() = tabular.getLastCellInRow(0);
3882                 else
3883                         cur.idx() = 0;
3884                 cur.pit() = 0;
3885                 cur.pos() = 0;
3886         } else {
3887                 if (isRightToLeft(cur))
3888                         cur.idx() = tabular.getFirstCellInRow(tabular.nrows() - 1);
3889                 else
3890                         cur.idx() = tabular.numberofcells - 1;
3891                 cur.pit() = 0;
3892                 cur.pos() = cur.lastpos(); // FIXME crude guess
3893         }
3894         cur.setCurrentFont();
3895         // FIXME: this accesses the position cache before it is initialized
3896         //resetPos(cur);
3897         //cur.bv().fitCursor();
3898 }
3899
3900
3901 void InsetTabular::updateBuffer(ParIterator const & it, UpdateType utype)
3902 {
3903         // In a longtable, tell captions what the current float is
3904         Counters & cnts = buffer().masterBuffer()->params().documentClass().counters();
3905         string const saveflt = cnts.current_float();
3906         if (tabular.is_long_tabular) {
3907                 cnts.current_float("table");
3908                 // in longtables, we only step the counter once
3909                 cnts.step(from_ascii("table"), utype);
3910                 cnts.isLongtable(true);
3911         }
3912
3913         ParIterator it2 = it;
3914         it2.forwardPos();
3915         size_t const end = it2.nargs();
3916         for ( ; it2.idx() < end; it2.top().forwardIdx())
3917                 buffer().updateBuffer(it2, utype);
3918
3919         //reset afterwards
3920         if (tabular.is_long_tabular) {
3921                 cnts.current_float(saveflt);
3922                 cnts.isLongtable(false);
3923         }
3924 }
3925
3926
3927 void InsetTabular::addToToc(DocIterator const & cpit, bool output_active) const
3928 {
3929         DocIterator dit = cpit;
3930         dit.forwardPos();
3931         size_t const end = dit.nargs();
3932         for ( ; dit.idx() < end; dit.top().forwardIdx())
3933                 cell(dit.idx())->addToToc(dit, output_active);
3934 }
3935
3936
3937 void InsetTabular::doDispatch(Cursor & cur, FuncRequest & cmd)
3938 {
3939         LYXERR(Debug::DEBUG, "# InsetTabular::doDispatch: cmd: " << cmd
3940                              << "\n  cur:" << cur);
3941         CursorSlice sl = cur.top();
3942         Cursor & bvcur = cur.bv().cursor();
3943
3944         FuncCode const act = cmd.action();
3945         
3946         switch (act) {
3947
3948         case LFUN_MOUSE_PRESS: {
3949                 //lyxerr << "# InsetTabular::MousePress\n" << cur.bv().cursor() << endl;
3950                 // select row
3951                 if (cmd.x() < xo(cur.bv()) + ADD_TO_TABULAR_WIDTH
3952                         || cmd.x() > xo(cur.bv()) + tabular.width()) {
3953                         row_type r = rowFromY(cur, cmd.y());
3954                         cur.idx() = tabular.getFirstCellInRow(r);
3955                         cur.pos() = 0;
3956                         cur.resetAnchor();
3957                         cur.idx() = tabular.getLastCellInRow(r);
3958                         cur.pos() = cur.lastpos();
3959                         cur.setSelection(true);
3960                         bvcur = cur; 
3961                         rowselect_ = true;
3962                         break;
3963                 }
3964                 // select column
3965                 int const y0 = yo(cur.bv()) - tabular.rowAscent(0) + offset_valign_;
3966                 if (cmd.y() < y0 + ADD_TO_TABULAR_WIDTH 
3967                         || cmd.y() > y0 + tabular.height()) {
3968                         col_type c = columnFromX(cur, cmd.x());
3969                         cur.idx() = tabular.cellIndex(0, c);
3970                         cur.pos() = 0;
3971                         cur.resetAnchor();
3972                         cur.idx() = tabular.cellIndex(tabular.nrows() - 1, c);
3973                         cur.pos() = cur.lastpos();
3974                         cur.setSelection(true);
3975                         bvcur = cur; 
3976                         colselect_ = true;
3977                         break;
3978                 }
3979                 // do not reset cursor/selection if we have selected
3980                 // some cells (bug 2715).
3981                 if (cmd.button() == mouse_button::button3
3982                     && &bvcur.selBegin().inset() == this 
3983                     && bvcur.selIsMultiCell()) 
3984                         ;
3985                 else
3986                         // Let InsetTableCell do it
3987                         cell(cur.idx())->dispatch(cur, cmd);
3988                 break;
3989         }
3990         case LFUN_MOUSE_MOTION:
3991                 //lyxerr << "# InsetTabular::MouseMotion\n" << bvcur << endl;
3992                 if (cmd.button() == mouse_button::button1) {
3993                         // only accept motions to places not deeper nested than the real anchor
3994                         if (!bvcur.realAnchor().hasPart(cur)) {
3995                                 cur.undispatched();
3996                                 break;
3997                         }
3998                         // select (additional) row
3999                         if (rowselect_) {
4000                                 row_type r = rowFromY(cur, cmd.y());
4001                                 cur.idx() = tabular.getLastCellInRow(r);
4002                                 // we need to reset the cursor's pit and pos now, as the old ones
4003                                 // may no longer be valid.
4004                                 cur.pit() = 0;
4005                                 cur.pos() = 0;
4006                                 bvcur.setCursor(cur);
4007                                 bvcur.setSelection(true);
4008                                 break;
4009                         }
4010                         // select (additional) column
4011                         if (colselect_) {
4012                                 col_type c = columnFromX(cur, cmd.x());
4013                                 cur.idx() = tabular.cellIndex(tabular.nrows() - 1, c);
4014                                 // we need to reset the cursor's pit and pos now, as the old ones
4015                                 // may no longer be valid.
4016                                 cur.pit() = 0;
4017                                 cur.pos() = 0;
4018                                 bvcur.setCursor(cur);
4019                                 bvcur.setSelection(true);
4020                                 break;
4021                         }
4022                         // only update if selection changes
4023                         if (bvcur.idx() == cur.idx() &&
4024                                 !(bvcur.realAnchor().idx() == cur.idx() && bvcur.pos() != cur.pos()))
4025                                 cur.noScreenUpdate();
4026                         setCursorFromCoordinates(cur, cmd.x(), cmd.y());
4027                         bvcur.setCursor(cur);
4028                         bvcur.setSelection(true);
4029                         // if this is a multicell selection, we just set the cursor to
4030                         // the beginning of the cell's text.
4031                         if (bvcur.selIsMultiCell()) {
4032                                 bvcur.pit() = bvcur.lastpit();
4033                                 bvcur.pos() = bvcur.lastpos();
4034                         }
4035                 }
4036                 break;
4037
4038         case LFUN_MOUSE_RELEASE:
4039                 rowselect_ = false;
4040                 colselect_ = false;
4041                 break;
4042
4043         case LFUN_CELL_BACKWARD:
4044                 movePrevCell(cur);
4045                 cur.setSelection(false);
4046                 break;
4047
4048         case LFUN_CELL_FORWARD:
4049                 moveNextCell(cur);
4050                 cur.setSelection(false);
4051                 break;
4052
4053         case LFUN_CHAR_FORWARD_SELECT:
4054         case LFUN_CHAR_FORWARD:
4055         case LFUN_CHAR_BACKWARD_SELECT:
4056         case LFUN_CHAR_BACKWARD:
4057         case LFUN_CHAR_RIGHT_SELECT:
4058         case LFUN_CHAR_RIGHT:
4059         case LFUN_CHAR_LEFT_SELECT:
4060         case LFUN_CHAR_LEFT: 
4061         case LFUN_WORD_FORWARD:
4062         case LFUN_WORD_FORWARD_SELECT:
4063         case LFUN_WORD_BACKWARD:
4064         case LFUN_WORD_BACKWARD_SELECT:
4065         case LFUN_WORD_RIGHT:
4066         case LFUN_WORD_RIGHT_SELECT:
4067         case LFUN_WORD_LEFT:
4068         case LFUN_WORD_LEFT_SELECT: {
4069                 // determine whether we move to next or previous cell, where to enter 
4070                 // the new cell from, and which command to "finish" (i.e., exit the
4071                 // inset) with:
4072                 bool next_cell;
4073                 EntryDirection entry_from = ENTRY_DIRECTION_IGNORE;
4074                 FuncCode finish_lfun;
4075
4076                 if (act == LFUN_CHAR_FORWARD 
4077                                 || act == LFUN_CHAR_FORWARD_SELECT
4078                                 || act == LFUN_WORD_FORWARD
4079                                 || act == LFUN_WORD_FORWARD_SELECT) {
4080                         next_cell = true;
4081                         finish_lfun = LFUN_FINISHED_FORWARD;
4082                 }
4083                 else if (act == LFUN_CHAR_BACKWARD
4084                                 || act == LFUN_CHAR_BACKWARD_SELECT
4085                                 || act == LFUN_WORD_BACKWARD
4086                                 || act == LFUN_WORD_BACKWARD_SELECT) {
4087                         next_cell = false;
4088                         finish_lfun = LFUN_FINISHED_BACKWARD;
4089                 }
4090                 // LEFT or RIGHT commands --- the interpretation will depend on the 
4091                 // table's direction.
4092                 else {
4093                         bool const right = act == LFUN_CHAR_RIGHT
4094                                 || act == LFUN_CHAR_RIGHT_SELECT
4095                                 || act == LFUN_WORD_RIGHT
4096                                 || act == LFUN_WORD_RIGHT_SELECT;
4097                         next_cell = isRightToLeft(cur) != right;
4098                         
4099                         if (lyxrc.visual_cursor)
4100                                 entry_from = right ? ENTRY_DIRECTION_LEFT:ENTRY_DIRECTION_RIGHT;
4101
4102                         finish_lfun = right ? LFUN_FINISHED_RIGHT : LFUN_FINISHED_LEFT;
4103                 }
4104
4105                 bool const select =     act == LFUN_CHAR_FORWARD_SELECT 
4106                     || act == LFUN_CHAR_BACKWARD_SELECT
4107                     || act == LFUN_CHAR_RIGHT_SELECT
4108                     || act == LFUN_CHAR_LEFT_SELECT
4109                         || act == LFUN_WORD_FORWARD_SELECT
4110                         || act == LFUN_WORD_RIGHT_SELECT
4111                         || act == LFUN_WORD_BACKWARD_SELECT
4112                         || act == LFUN_WORD_LEFT_SELECT;
4113
4114                 // If we have a multicell selection or we're 
4115                 // not doing some LFUN_*_SELECT thing anyway...
4116                 if (!cur.selIsMultiCell() || !select) {
4117                         col_type const c = tabular.cellColumn(cur.idx());
4118                         row_type const r = tabular.cellRow(cur.idx());
4119                         // Are we trying to select the whole cell and is the whole cell 
4120                         // not yet selected?
4121                         bool const select_whole = select && !isCellSelected(cur, r, c) &&
4122                                 ((next_cell && cur.pit() == cur.lastpit() 
4123                                 && cur.pos() == cur.lastpos())
4124                                 || (!next_cell && cur.pit() == 0 && cur.pos() == 0));
4125
4126                         bool const empty_cell = cur.lastpos() == 0 && cur.lastpit() == 0;
4127
4128                         // ...try to dispatch to the cell's inset.
4129                         cell(cur.idx())->dispatch(cur, cmd);
4130
4131                         // When we already have a selection we want to select the whole cell
4132                         // before going to the next cell.
4133                         if (select_whole && !empty_cell){
4134                                 getText(cur.idx())->selectAll(cur);
4135                                 cur.dispatched();
4136                                 cur.screenUpdateFlags(Update::Force | Update::FitCursor);
4137                                 break;
4138                         }
4139
4140                         // FIXME: When we support the selection of an empty cell, remove 
4141                         // the !empty_cell from this condition. For now we jump to the next
4142                         // cell if the current cell is empty.
4143                         if (cur.result().dispatched() && !empty_cell)
4144                                 break;
4145                 }
4146
4147                 // move to next/prev cell, as appropriate
4148                 // note that we will always do this if we're selecting and we have
4149                 // a multicell selection
4150                 LYXERR(Debug::RTL, "entering " << (next_cell ? "next" : "previous")
4151                         << " cell from: " << int(entry_from));
4152                 if (next_cell)
4153                         moveNextCell(cur, entry_from);
4154                 else
4155                         movePrevCell(cur, entry_from);
4156                 // if we're exiting the table, call the appropriate FINISHED lfun
4157                 if (sl == cur.top())
4158                         cmd = FuncRequest(finish_lfun);
4159                 else
4160                         cur.dispatched();
4161
4162                 cur.screenUpdateFlags(Update::Force | Update::FitCursor);
4163                 break;
4164
4165         }
4166
4167         case LFUN_DOWN_SELECT:
4168         case LFUN_DOWN:
4169                 if (!(cur.selection() && cur.selIsMultiCell()))
4170                         cell(cur.idx())->dispatch(cur, cmd);
4171                 
4172                 cur.dispatched(); // override the cell's decision
4173                 if (sl == cur.top()) {
4174                         // if our Text didn't do anything to the cursor
4175                         // then we try to put the cursor into the cell below
4176                         // setting also the right targetX.
4177                         cur.selHandle(act == LFUN_DOWN_SELECT);
4178                         if (tabular.cellRow(cur.idx()) != tabular.nrows() - 1) {
4179                                 int const xtarget = cur.targetX();
4180                                 // WARNING: Once cur.idx() has been reset, the cursor is in
4181                                 // an inconsistent state until pos() has been set. Be careful
4182                                 // what you do with it!
4183                                 cur.idx() = tabular.cellBelow(cur.idx());
4184                                 cur.pit() = 0;
4185                                 TextMetrics const & tm =
4186                                         cur.bv().textMetrics(cell(cur.idx())->getText(0));
4187                                 cur.pos() = tm.x2pos(cur.pit(), 0, xtarget);
4188                                 cur.setCurrentFont();
4189                         }
4190                 }
4191                 if (sl == cur.top()) {
4192                         // we trick it to go to forward after leaving the
4193                         // tabular.
4194                         cmd = FuncRequest(LFUN_FINISHED_FORWARD);
4195                         cur.undispatched();
4196                 }
4197                 if (cur.selIsMultiCell()) {
4198                         cur.pit() = cur.lastpit();
4199                         cur.pos() = cur.lastpos();
4200                         cur.setCurrentFont();
4201                         cur.screenUpdateFlags(Update::Force | Update::FitCursor);
4202                         return;
4203                 }
4204                 cur.screenUpdateFlags(Update::Force | Update::FitCursor);
4205                 break;
4206
4207         case LFUN_UP_SELECT:
4208         case LFUN_UP:
4209                 if (!(cur.selection() && cur.selIsMultiCell()))
4210                         cell(cur.idx())->dispatch(cur, cmd);
4211                 cur.dispatched(); // override the cell's decision
4212                 if (sl == cur.top()) {
4213                         // if our Text didn't do anything to the cursor
4214                         // then we try to put the cursor into the cell above
4215                         // setting also the right targetX.
4216                         cur.selHandle(act == LFUN_UP_SELECT);
4217                         if (tabular.cellRow(cur.idx()) != 0) {
4218                                 int const xtarget = cur.targetX();
4219                                 // WARNING: Once cur.idx() has been reset, the cursor is in
4220                                 // an inconsistent state until pos() has been set. Be careful
4221                                 // what you do with it!
4222                                 cur.idx() = tabular.cellAbove(cur.idx());
4223                                 cur.pit() = cur.lastpit();
4224                                 Text const * text = cell(cur.idx())->getText(0);
4225                                 TextMetrics const & tm = cur.bv().textMetrics(text);
4226                                 ParagraphMetrics const & pm =
4227                                         tm.parMetrics(cur.lastpit());
4228                                 cur.pos() = tm.x2pos(cur.pit(), pm.rows().size()-1, xtarget);
4229                                 cur.setCurrentFont();
4230                         }
4231                 }
4232                 if (sl == cur.top()) {
4233                         cmd = FuncRequest(LFUN_UP);
4234                         cur.undispatched();
4235                 }
4236                 if (cur.selIsMultiCell()) {
4237                         cur.pit() = 0;
4238                         cur.pos() = cur.lastpos();
4239                         cur.setCurrentFont();
4240                         cur.screenUpdateFlags(Update::Force | Update::FitCursor);
4241                         return;
4242                 }
4243                 cur.screenUpdateFlags(Update::Force | Update::FitCursor);
4244                 break;
4245
4246 //      case LFUN_SCREEN_DOWN: {
4247 //              //if (hasSelection())
4248 //              //      cur.selection() = false;
4249 //              col_type const col = tabular.cellColumn(cur.idx());
4250 //              int const t =   cur.bv().top_y() + cur.bv().height();
4251 //              if (t < yo() + tabular.getHeightOfTabular()) {
4252 //                      cur.bv().scrollDocView(t, true);
4253 //                      cur.idx() = tabular.cellBelow(first_visible_cell) + col;
4254 //              } else {
4255 //                      cur.idx() = tabular.getFirstCellInRow(tabular.rows() - 1) + col;
4256 //              }
4257 //              cur.par() = 0;
4258 //              cur.pos() = 0;
4259 //              break;
4260 //      }
4261 //
4262 //      case LFUN_SCREEN_UP: {
4263 //              //if (hasSelection())
4264 //              //      cur.selection() = false;
4265 //              col_type const col = tabular.cellColumn(cur.idx());
4266 //              int const t =   cur.bv().top_y() + cur.bv().height();
4267 //              if (yo() < 0) {
4268 //                      cur.bv().scrollDocView(t, true);
4269 //                      if (yo() > 0)
4270 //                              cur.idx() = col;
4271 //                      else
4272 //                              cur.idx() = tabular.cellBelow(first_visible_cell) + col;
4273 //              } else {
4274 //                      cur.idx() = col;
4275 //              }
4276 //              cur.par() = cur.lastpar();
4277 //              cur.pos() = cur.lastpos();
4278 //              break;
4279 //      }
4280
4281         case LFUN_LAYOUT_TABULAR:
4282                 cur.bv().showDialog("tabular");
4283                 break;
4284
4285         case LFUN_INSET_MODIFY: {
4286                 string arg;
4287                 if (cmd.getArg(1) == "from-dialog")
4288                         arg = cmd.getArg(0) + to_utf8(cmd.argument().substr(19));
4289                 else
4290                         arg = to_utf8(cmd.argument());
4291                 if (!tabularFeatures(cur, arg))
4292                         cur.undispatched();
4293                 break;
4294         }
4295
4296         // insert file functions
4297         case LFUN_FILE_INSERT_PLAINTEXT_PARA:
4298         case LFUN_FILE_INSERT_PLAINTEXT:
4299                 // FIXME UNICODE
4300                 if (FileName::isAbsolute(to_utf8(cmd.argument()))) {
4301                         docstring const tmpstr = cur.bv().contentsOfPlaintextFile(
4302                                 FileName(to_utf8(cmd.argument())));
4303                         if (tmpstr.empty())
4304                                 break;
4305                         cur.recordUndoInset(INSERT_UNDO);
4306                         if (insertPlaintextString(cur.bv(), tmpstr, false)) {
4307                                 // content has been replaced,
4308                                 // so cursor might be invalid
4309                                 cur.pos() = cur.lastpos();
4310                                 cur.pit() = cur.lastpit();
4311                                 bvcur.setCursor(cur);
4312                         } else
4313                                 cur.undispatched();
4314                 }
4315                 break;
4316
4317         case LFUN_CUT:
4318                 if (cur.selIsMultiCell()) {
4319                         if (copySelection(cur)) {
4320                                 cur.recordUndoInset(DELETE_UNDO);
4321                                 cutSelection(cur);
4322                         }
4323                 } else
4324                         cell(cur.idx())->dispatch(cur, cmd);
4325                 break;
4326
4327         case LFUN_SELF_INSERT:
4328                 if (cur.selIsMultiCell()) {
4329                         cur.recordUndoInset(DELETE_UNDO);
4330                         cutSelection(cur);
4331                 }
4332                 cell(cur.idx())->dispatch(cur, cmd);
4333                 break;
4334
4335         case LFUN_CHAR_DELETE_BACKWARD:
4336         case LFUN_CHAR_DELETE_FORWARD:
4337                 if (cur.selIsMultiCell()) {
4338                         cur.recordUndoInset(DELETE_UNDO);
4339                         cutSelection(cur);
4340                 } else
4341                         cell(cur.idx())->dispatch(cur, cmd);
4342                 break;
4343
4344         case LFUN_COPY:
4345                 if (!cur.selection())
4346                         break;
4347                 if (cur.selIsMultiCell()) {
4348                         cur.finishUndo();
4349                         copySelection(cur);
4350                 } else
4351                         cell(cur.idx())->dispatch(cur, cmd);
4352                 break;
4353
4354         case LFUN_CLIPBOARD_PASTE:
4355         case LFUN_PRIMARY_SELECTION_PASTE: {
4356                 docstring const clip = (act == LFUN_CLIPBOARD_PASTE) ?
4357                         theClipboard().getAsText(Clipboard::PlainTextType) :
4358                         theSelection().get();
4359                 if (clip.empty())
4360                         break;
4361                 // pass to InsertPlaintextString, but
4362                 // only if we have multi-cell content
4363                 if (clip.find_first_of(from_ascii("\t\n")) != docstring::npos) {
4364                         cur.recordUndoInset(INSERT_UNDO);
4365                         if (insertPlaintextString(cur.bv(), clip, false)) {
4366                                 // content has been replaced,
4367                                 // so cursor might be invalid
4368                                 cur.pos() = cur.lastpos();
4369                                 cur.pit() = cur.lastpit();
4370                                 bvcur.setCursor(cur);
4371                                 break;
4372                         }
4373                 }
4374                 // Let the cell handle normal text
4375                 cell(cur.idx())->dispatch(cur, cmd);
4376                 break;
4377         }
4378
4379         case LFUN_PASTE:
4380                 if (!tabularStackDirty()) {
4381                         if (!cur.selIsMultiCell())
4382                                 cell(cur.idx())->dispatch(cur, cmd);
4383                         break;
4384                 }
4385                 if (theClipboard().isInternal()) {
4386                         cur.recordUndoInset(INSERT_UNDO);
4387                         pasteClipboard(cur);
4388                 }
4389                 break;
4390
4391         case LFUN_FONT_EMPH:
4392         case LFUN_FONT_BOLD:
4393         case LFUN_FONT_BOLDSYMBOL:
4394         case LFUN_FONT_ROMAN:
4395         case LFUN_FONT_NOUN:
4396         case LFUN_FONT_ITAL:
4397         case LFUN_FONT_FRAK:
4398         case LFUN_FONT_TYPEWRITER:
4399         case LFUN_FONT_SANS:
4400         case LFUN_TEXTSTYLE_APPLY:
4401         case LFUN_TEXTSTYLE_UPDATE:
4402         case LFUN_FONT_SIZE:
4403         case LFUN_FONT_UNDERLINE:
4404         case LFUN_FONT_STRIKEOUT:
4405         case LFUN_FONT_UNDERUNDERLINE:
4406         case LFUN_FONT_UNDERWAVE:
4407         case LFUN_LANGUAGE:
4408         case LFUN_PARAGRAPH_PARAMS_APPLY:
4409         case LFUN_PARAGRAPH_PARAMS:
4410         case LFUN_WORD_CAPITALIZE:
4411         case LFUN_WORD_UPCASE:
4412         case LFUN_WORD_LOWCASE:
4413         case LFUN_CHARS_TRANSPOSE:
4414                 if (cur.selIsMultiCell()) {
4415                         row_type rs, re;
4416                         col_type cs, ce;
4417                         getSelection(cur, rs, re, cs, ce);
4418                         Cursor tmpcur = cur;
4419                         for (row_type r = rs; r <= re; ++r) {
4420                                 for (col_type c = cs; c <= ce; ++c) {
4421                                         // cursor follows cell:
4422                                         tmpcur.idx() = tabular.cellIndex(r, c);
4423                                         // select this cell only:
4424                                         tmpcur.pit() = 0;
4425                                         tmpcur.pos() = 0;
4426                                         tmpcur.resetAnchor();
4427                                         tmpcur.pit() = tmpcur.lastpit();
4428                                         tmpcur.pos() = tmpcur.top().lastpos();
4429                                         tmpcur.setCursor(tmpcur);
4430                                         tmpcur.setSelection();
4431                                         cell(tmpcur.idx())->dispatch(tmpcur, cmd);
4432                                 }
4433                         }
4434                         break;
4435                 } else {
4436                         cell(cur.idx())->dispatch(cur, cmd);
4437                         break;
4438                 }
4439
4440         case LFUN_INSET_SETTINGS:
4441                 // relay this lfun to Inset, not to the cell.
4442                 Inset::doDispatch(cur, cmd);
4443                 break;
4444
4445         default:
4446                 // we try to handle this event in the insets dispatch function.
4447                 cell(cur.idx())->dispatch(cur, cmd);
4448                 break;
4449         }
4450 }
4451
4452
4453 // function sets an object as defined in func_status.h:
4454 // states OK, Unknown, Disabled, On, Off.
4455 bool InsetTabular::getStatus(Cursor & cur, FuncRequest const & cmd,
4456         FuncStatus & status) const
4457 {
4458         switch (cmd.action()) {
4459         case LFUN_INSET_MODIFY: {
4460                 if (&cur.inset() != this || cmd.getArg(0) != "tabular") 
4461                         break;
4462
4463                 // FIXME: We only check for the very first argument...
4464                 string const s = cmd.getArg(1);
4465                 // We always enable the lfun if it is coming from the dialog
4466                 // because the dialog makes sure all the settings are valid,
4467                 // even though the first argument might not be valid now.
4468                 if (s == "from-dialog") {
4469                         status.setEnabled(true);
4470                         return true;
4471                 }
4472
4473                 int action = Tabular::LAST_ACTION;
4474                 int i = 0;
4475                 for (; tabularFeature[i].action != Tabular::LAST_ACTION; ++i) {
4476                         if (tabularFeature[i].feature == s) {
4477                                 action = tabularFeature[i].action;
4478                                 break;
4479                         }
4480                 }
4481                 if (action == Tabular::LAST_ACTION) {
4482                         status.clear();
4483                         status.setUnknown(true);
4484                         return true;
4485                 }
4486
4487                 string const argument = cmd.getLongArg(2);
4488
4489                 row_type sel_row_start = 0;
4490                 row_type sel_row_end = 0;
4491                 col_type sel_col_start = 0;
4492                 col_type sel_col_end = 0;
4493                 Tabular::ltType dummyltt;
4494                 bool flag = true;
4495
4496                 getSelection(cur, sel_row_start, sel_row_end, sel_col_start, sel_col_end);
4497
4498                 switch (action) {
4499                 case Tabular::SET_PWIDTH:
4500                 case Tabular::SET_MPWIDTH:
4501                 case Tabular::SET_SPECIAL_COLUMN:
4502                 case Tabular::SET_SPECIAL_MULTICOLUMN:
4503                 case Tabular::APPEND_ROW:
4504                 case Tabular::APPEND_COLUMN:
4505                 case Tabular::DELETE_ROW:
4506                 case Tabular::DELETE_COLUMN:
4507                 case Tabular::COPY_ROW:
4508                 case Tabular::COPY_COLUMN:
4509                 case Tabular::SET_TOP_SPACE:
4510                 case Tabular::SET_BOTTOM_SPACE:
4511                 case Tabular::SET_INTERLINE_SPACE:
4512                         status.clear();
4513                         return true;
4514
4515                 case Tabular::SET_TABULAR_WIDTH:
4516                         status.setEnabled(!tabular.rotate &&  !tabular.is_long_tabular
4517                                 && tabular.tabular_valignment == Tabular::LYX_VALIGN_MIDDLE);
4518                         break;
4519
4520                 case Tabular::MOVE_COLUMN_RIGHT:
4521                 case Tabular::MOVE_COLUMN_LEFT:
4522                 case Tabular::MOVE_ROW_DOWN:
4523                 case Tabular::MOVE_ROW_UP: {
4524                         if (cur.selection()) {
4525                                 status.message(_("Selections not supported."));
4526                                 status.setEnabled(false);
4527                                 break;
4528                         }
4529
4530                         if ((action == Tabular::MOVE_COLUMN_RIGHT &&
4531                                 tabular.ncols() == tabular.cellColumn(cur.idx()) + 1) ||
4532                             (action == Tabular::MOVE_COLUMN_LEFT &&
4533                                 tabular.cellColumn(cur.idx()) == 0) ||
4534                             (action == Tabular::MOVE_ROW_DOWN &&
4535                                 tabular.nrows() == tabular.cellRow(cur.idx()) + 1) ||
4536                             (action == Tabular::MOVE_ROW_UP &&
4537                                 tabular.cellRow(cur.idx()) == 0)) {
4538                                         status.setEnabled(false);
4539                                         break;
4540                         }
4541
4542                         if (action == Tabular::MOVE_COLUMN_RIGHT ||
4543                             action == Tabular::MOVE_COLUMN_LEFT) {
4544                                 if (tabular.hasMultiColumn(tabular.cellColumn(cur.idx())) ||
4545                                     tabular.hasMultiColumn(tabular.cellColumn(cur.idx()) +
4546                                         (action == Tabular::MOVE_COLUMN_RIGHT ? 1 : -1))) {
4547                                         status.message(_("Multi-column in current or"
4548                                                          " destination column."));
4549                                         status.setEnabled(false);
4550                                         break;
4551                                 }
4552                         }
4553
4554                         if (action == Tabular::MOVE_ROW_DOWN ||
4555                             action == Tabular::MOVE_ROW_UP) {
4556                                 if (tabular.hasMultiRow(tabular.cellRow(cur.idx())) ||
4557                                     tabular.hasMultiRow(tabular.cellRow(cur.idx()) +
4558                                         (action == Tabular::MOVE_ROW_DOWN ? 1 : -1))) {
4559                                         status.message(_("Multi-row in current or"
4560                                                          " destination row."));
4561                                         status.setEnabled(false);
4562                                         break;
4563                                 }
4564                         }
4565
4566                         status.setEnabled(true);
4567                         break;
4568                 }
4569
4570                 case Tabular::SET_DECIMAL_POINT:
4571                         status.setEnabled(
4572                                 tabular.getAlignment(cur.idx()) == LYX_ALIGN_DECIMAL);
4573                         break;
4574
4575                 case Tabular::SET_MULTICOLUMN:
4576                 case Tabular::UNSET_MULTICOLUMN:
4577                 case Tabular::MULTICOLUMN:
4578                         // If a row is set as longtable caption, it must not be allowed
4579                         // to unset that this row is a multicolumn.
4580                         status.setEnabled(sel_row_start == sel_row_end
4581                                 && !tabular.ltCaption(tabular.cellRow(cur.idx())));
4582                         status.setOnOff(tabular.isMultiColumn(cur.idx()));
4583                         break;
4584
4585                 case Tabular::SET_MULTIROW:
4586                 case Tabular::UNSET_MULTIROW:
4587                 case Tabular::MULTIROW:
4588                         // If a row is set as longtable caption, it must not be allowed
4589                         // to unset that this row is a multirow.
4590                         status.setEnabled(sel_col_start == sel_col_end
4591                                 && !tabular.ltCaption(tabular.cellRow(cur.idx())));
4592                         status.setOnOff(tabular.isMultiRow(cur.idx()));
4593                         break;
4594
4595                 case Tabular::SET_ALL_LINES:
4596                 case Tabular::UNSET_ALL_LINES:
4597                 case Tabular::SET_BORDER_LINES:
4598                         status.setEnabled(!tabular.ltCaption(tabular.cellRow(cur.idx())));
4599                         break;
4600
4601                 case Tabular::SET_LINE_TOP:
4602                 case Tabular::SET_LINE_BOTTOM:
4603                 case Tabular::SET_LINE_LEFT:
4604                 case Tabular::SET_LINE_RIGHT:
4605                         status.setEnabled(!tabular.ltCaption(tabular.cellRow(cur.idx())));
4606                         break;
4607
4608                 case Tabular::TOGGLE_LINE_TOP:
4609                         status.setEnabled(!tabular.ltCaption(tabular.cellRow(cur.idx())));
4610                         status.setOnOff(tabular.topLine(cur.idx()));
4611                         break;
4612
4613                 case Tabular::TOGGLE_LINE_BOTTOM:
4614                         status.setEnabled(!tabular.ltCaption(tabular.cellRow(cur.idx())));
4615                         status.setOnOff(tabular.bottomLine(cur.idx()));
4616                         break;
4617
4618                 case Tabular::TOGGLE_LINE_LEFT:
4619                         status.setEnabled(!tabular.ltCaption(tabular.cellRow(cur.idx())));
4620                         status.setOnOff(tabular.leftLine(cur.idx()));
4621                         break;
4622
4623                 case Tabular::TOGGLE_LINE_RIGHT:
4624                         status.setEnabled(!tabular.ltCaption(tabular.cellRow(cur.idx())));
4625                         status.setOnOff(tabular.rightLine(cur.idx()));
4626                         break;
4627
4628                 // multirow cells only inherit the alignment of the column if the column has
4629                 // no width, otherwise they are left-aligned
4630                 // therefore allow always left but right and center only if there is no width
4631                 case Tabular::M_ALIGN_LEFT:
4632                         flag = false;
4633                 case Tabular::ALIGN_LEFT:
4634                         status.setOnOff(tabular.getAlignment(cur.idx(), flag) == LYX_ALIGN_LEFT);
4635                         break;
4636
4637                 case Tabular::M_ALIGN_RIGHT:
4638                         flag = false;
4639                 case Tabular::ALIGN_RIGHT:
4640                         status.setEnabled(!(tabular.isMultiRow(cur.idx()) 
4641                                 && !tabular.getPWidth(cur.idx()).zero()));
4642                         status.setOnOff(tabular.getAlignment(cur.idx(), flag) == LYX_ALIGN_RIGHT);
4643                         break;
4644
4645                 case Tabular::M_ALIGN_CENTER:
4646                         flag = false;
4647                 case Tabular::ALIGN_CENTER:
4648                         status.setEnabled(!(tabular.isMultiRow(cur.idx()) 
4649                                 && !tabular.getPWidth(cur.idx()).zero()));
4650                         status.setOnOff(tabular.getAlignment(cur.idx(), flag) == LYX_ALIGN_CENTER);
4651                         break;
4652
4653                 case Tabular::ALIGN_BLOCK:
4654                         status.setEnabled(!tabular.getPWidth(cur.idx()).zero()
4655                                 && !tabular.isMultiRow(cur.idx()));
4656                         status.setOnOff(tabular.getAlignment(cur.idx(), flag) == LYX_ALIGN_BLOCK);
4657                         break;
4658
4659                 case Tabular::ALIGN_DECIMAL:
4660                         status.setEnabled(!tabular.isMultiRow(cur.idx()) 
4661                                 && !tabular.isMultiColumn(cur.idx()));
4662                         status.setOnOff(tabular.getAlignment(cur.idx(), true) == LYX_ALIGN_DECIMAL);
4663                         break;
4664
4665                 case Tabular::M_VALIGN_TOP:
4666                         flag = false;
4667                 case Tabular::VALIGN_TOP:
4668                         status.setEnabled(!tabular.getPWidth(cur.idx()).zero()
4669                                 && !tabular.isMultiRow(cur.idx()));
4670                         status.setOnOff(
4671                                 tabular.getVAlignment(cur.idx(), flag) == Tabular::LYX_VALIGN_TOP);
4672                         break;
4673
4674                 case Tabular::M_VALIGN_BOTTOM:
4675                         flag = false;
4676                 case Tabular::VALIGN_BOTTOM:
4677                         status.setEnabled(!tabular.getPWidth(cur.idx()).zero()
4678                                 && !tabular.isMultiRow(cur.idx()));
4679                         status.setOnOff(
4680                                 tabular.getVAlignment(cur.idx(), flag) == Tabular::LYX_VALIGN_BOTTOM);
4681                         break;
4682
4683                 case Tabular::M_VALIGN_MIDDLE:
4684                         flag = false;
4685                 case Tabular::VALIGN_MIDDLE:
4686                         status.setEnabled(!tabular.getPWidth(cur.idx()).zero()
4687                                 && !tabular.isMultiRow(cur.idx()));
4688                         status.setOnOff(
4689                                 tabular.getVAlignment(cur.idx(), flag) == Tabular::LYX_VALIGN_MIDDLE);
4690                         break;
4691
4692                 case Tabular::SET_LONGTABULAR:
4693                         // setting as longtable is not allowed when table is inside a float
4694                         if (cur.innerInsetOfType(FLOAT_CODE) != 0
4695                                 || cur.innerInsetOfType(WRAP_CODE) != 0)
4696                                 status.setEnabled(false);
4697                         else
4698                                 status.setEnabled(true);
4699                         status.setOnOff(tabular.is_long_tabular);
4700                         break;
4701
4702                 case Tabular::UNSET_LONGTABULAR:
4703                         status.setOnOff(!tabular.is_long_tabular);
4704                         break;
4705
4706                 case Tabular::TOGGLE_ROTATE_TABULAR:
4707                 case Tabular::SET_ROTATE_TABULAR:
4708                         status.setOnOff(tabular.rotate != 0);
4709                         break;
4710
4711                 case Tabular::TABULAR_VALIGN_TOP:
4712                         status.setEnabled(tabular.tabular_width.zero());
4713                         status.setOnOff(tabular.tabular_valignment 
4714                                 == Tabular::LYX_VALIGN_TOP);
4715                         break;
4716                 case Tabular::TABULAR_VALIGN_MIDDLE:
4717                         status.setEnabled(tabular.tabular_width.zero());
4718                         status.setOnOff(tabular.tabular_valignment 
4719                                 == Tabular::LYX_VALIGN_MIDDLE);
4720                         break;
4721                 case Tabular::TABULAR_VALIGN_BOTTOM:
4722                         status.setEnabled(tabular.tabular_width.zero());
4723                         status.setOnOff(tabular.tabular_valignment 
4724                                 == Tabular::LYX_VALIGN_BOTTOM);
4725                         break;
4726
4727                 case Tabular::LONGTABULAR_ALIGN_LEFT:
4728                         status.setOnOff(tabular.longtabular_alignment 
4729                                 == Tabular::LYX_LONGTABULAR_ALIGN_LEFT);
4730                         break;
4731                 case Tabular::LONGTABULAR_ALIGN_CENTER:
4732                         status.setOnOff(tabular.longtabular_alignment 
4733                                 == Tabular::LYX_LONGTABULAR_ALIGN_CENTER);
4734                         break;
4735                 case Tabular::LONGTABULAR_ALIGN_RIGHT:
4736                         status.setOnOff(tabular.longtabular_alignment 
4737                                 == Tabular::LYX_LONGTABULAR_ALIGN_RIGHT);
4738                         break;
4739
4740                 case Tabular::UNSET_ROTATE_TABULAR:
4741                         status.setOnOff(tabular.rotate == 0);
4742                         break;
4743
4744                 case Tabular::TOGGLE_ROTATE_CELL:
4745                 case Tabular::SET_ROTATE_CELL:
4746                         status.setOnOff(!oneCellHasRotationState(false,
4747                                 sel_row_start, sel_row_end, sel_col_start, sel_col_end));
4748                         break;
4749
4750                 case Tabular::UNSET_ROTATE_CELL:
4751                         status.setOnOff(!oneCellHasRotationState(true,
4752                                 sel_row_start, sel_row_end, sel_col_start, sel_col_end));
4753                         break;
4754
4755                 case Tabular::SET_USEBOX:
4756                         status.setOnOff(convert<int>(argument) == tabular.getUsebox(cur.idx()));
4757                         break;
4758
4759                 // every row can only be one thing:
4760                 // either a footer or header
4761                 case Tabular::SET_LTFIRSTHEAD:
4762                         status.setEnabled(sel_row_start == sel_row_end);
4763                         status.setOnOff(tabular.getRowOfLTFirstHead(sel_row_start, dummyltt));
4764                         break;
4765
4766                 case Tabular::UNSET_LTFIRSTHEAD:
4767                         status.setEnabled(sel_row_start == sel_row_end);
4768                         status.setOnOff(!tabular.getRowOfLTFirstHead(sel_row_start, dummyltt));
4769                         break;
4770
4771                 case Tabular::SET_LTHEAD:
4772                         status.setEnabled(sel_row_start == sel_row_end);
4773                         status.setOnOff(tabular.getRowOfLTHead(sel_row_start, dummyltt));
4774                         break;
4775
4776                 case Tabular::UNSET_LTHEAD:
4777                         status.setEnabled(sel_row_start == sel_row_end);
4778                         status.setOnOff(!tabular.getRowOfLTHead(sel_row_start, dummyltt));
4779                         break;
4780
4781                 case Tabular::SET_LTFOOT:
4782                         status.setEnabled(sel_row_start == sel_row_end);
4783                         status.setOnOff(tabular.getRowOfLTFoot(sel_row_start, dummyltt));
4784                         break;
4785
4786                 case Tabular::UNSET_LTFOOT:
4787                         status.setEnabled(sel_row_start == sel_row_end);
4788                         status.setOnOff(!tabular.getRowOfLTFoot(sel_row_start, dummyltt));
4789                         break;
4790
4791                 case Tabular::SET_LTLASTFOOT:
4792                         status.setEnabled(sel_row_start == sel_row_end);
4793                         status.setOnOff(tabular.getRowOfLTLastFoot(sel_row_start, dummyltt));
4794                         break;
4795
4796                 case Tabular::UNSET_LTLASTFOOT:
4797                         status.setEnabled(sel_row_start == sel_row_end);
4798                         status.setOnOff(!tabular.getRowOfLTLastFoot(sel_row_start, dummyltt));
4799                         break;
4800
4801                 case Tabular::SET_LTNEWPAGE:
4802                         status.setOnOff(tabular.getLTNewPage(sel_row_start));
4803                         break;
4804                 case Tabular::UNSET_LTNEWPAGE:
4805                         status.setOnOff(!tabular.getLTNewPage(sel_row_start));
4806                         break;
4807
4808                 // only one row in head/firsthead/foot/lasthead can be the caption
4809                 // and a multirow cannot be set as caption
4810                 case Tabular::SET_LTCAPTION:
4811                         status.setEnabled(sel_row_start == sel_row_end
4812                                 && (!tabular.getRowOfLTFirstHead(sel_row_start, dummyltt)
4813                                  || !tabular.haveLTCaption(Tabular::CAPTION_FIRSTHEAD))
4814                                 && (!tabular.getRowOfLTHead(sel_row_start, dummyltt)
4815                                  || !tabular.haveLTCaption(Tabular::CAPTION_HEAD))
4816                                 && (!tabular.getRowOfLTFoot(sel_row_start, dummyltt)
4817                                  || !tabular.haveLTCaption(Tabular::CAPTION_FOOT))
4818                                 && (!tabular.getRowOfLTLastFoot(sel_row_start, dummyltt)
4819                                  || !tabular.haveLTCaption(Tabular::CAPTION_LASTFOOT))
4820                                 && !tabular.isMultiRow(sel_row_start));
4821                         status.setOnOff(tabular.ltCaption(sel_row_start));
4822                         break;
4823
4824                 case Tabular::UNSET_LTCAPTION:
4825                         status.setEnabled(sel_row_start == sel_row_end && tabular.ltCaption(sel_row_start));
4826                         break;
4827
4828                 case Tabular::TOGGLE_LTCAPTION:
4829                         status.setEnabled(sel_row_start == sel_row_end && (tabular.ltCaption(sel_row_start)
4830                                 || ((!tabular.getRowOfLTFirstHead(sel_row_start, dummyltt)
4831                                   || !tabular.haveLTCaption(Tabular::CAPTION_FIRSTHEAD))
4832                                  && (!tabular.getRowOfLTHead(sel_row_start, dummyltt)
4833                                   || !tabular.haveLTCaption(Tabular::CAPTION_HEAD))
4834                                  && (!tabular.getRowOfLTFoot(sel_row_start, dummyltt)
4835                                   || !tabular.haveLTCaption(Tabular::CAPTION_FOOT))
4836                                  && (!tabular.getRowOfLTLastFoot(sel_row_start, dummyltt)
4837                                   || !tabular.haveLTCaption(Tabular::CAPTION_LASTFOOT)))));
4838                         status.setOnOff(tabular.ltCaption(sel_row_start));
4839                         break;
4840
4841                 case Tabular::SET_BOOKTABS:
4842                         status.setOnOff(tabular.use_booktabs);
4843                         break;
4844
4845                 case Tabular::UNSET_BOOKTABS:
4846                         status.setOnOff(!tabular.use_booktabs);
4847                         break;
4848
4849                 default:
4850                         status.clear();
4851                         status.setEnabled(false);
4852                         break;
4853                 }
4854                 return true;
4855         }
4856
4857         case LFUN_CAPTION_INSERT: {
4858                 // caption is only allowed in caption cell of longtable
4859                 if (!tabular.ltCaption(tabular.cellRow(cur.idx()))) {
4860                         status.setEnabled(false);
4861                         return true;
4862                 }
4863                 // only standard caption is allowed
4864                 string arg = cmd.getArg(0);
4865                 if (!arg.empty() && arg != "Standard") {
4866                         status.setEnabled(false);
4867                         return true;
4868                 }
4869                 // check if there is already a caption
4870                 bool have_caption = false;
4871                 InsetTableCell itc = InsetTableCell(*tabular.cellInset(cur.idx()).get());
4872                 ParagraphList::const_iterator pit = itc.paragraphs().begin();
4873                 ParagraphList::const_iterator pend = itc.paragraphs().end();
4874                 for (; pit != pend; ++pit) {
4875                         InsetList::const_iterator it  = pit->insetList().begin();
4876                         InsetList::const_iterator end = pit->insetList().end();
4877                         for (; it != end; ++it) {
4878                                 if (it->inset->lyxCode() == CAPTION_CODE) {
4879                                         have_caption = true;
4880                                         break;
4881                                 }
4882                         }
4883                 }
4884                 status.setEnabled(!have_caption);
4885                 return true;
4886         }
4887
4888         // These are only enabled inside tabular
4889         case LFUN_CELL_BACKWARD:
4890         case LFUN_CELL_FORWARD:
4891                 status.setEnabled(true);
4892                 return true;
4893
4894         // disable these with multiple cells selected
4895         case LFUN_INSET_INSERT:
4896         case LFUN_TABULAR_INSERT:
4897         case LFUN_FLEX_INSERT:
4898         case LFUN_FLOAT_INSERT:
4899         case LFUN_FLOAT_WIDE_INSERT:
4900         case LFUN_FOOTNOTE_INSERT:
4901         case LFUN_MARGINALNOTE_INSERT:
4902         case LFUN_MATH_INSERT:
4903         case LFUN_MATH_MODE:
4904         case LFUN_MATH_MUTATE:
4905         case LFUN_MATH_DISPLAY:
4906         case LFUN_NOTE_INSERT:
4907         case LFUN_ARGUMENT_INSERT:
4908         case LFUN_BOX_INSERT:
4909         case LFUN_BRANCH_INSERT:
4910         case LFUN_PHANTOM_INSERT:
4911         case LFUN_WRAP_INSERT:
4912         case LFUN_PREVIEW_INSERT:
4913         case LFUN_ERT_INSERT: {
4914                 if (cur.selIsMultiCell()) {
4915                         status.setEnabled(false);
4916                         return true;
4917                 } else
4918                         return cell(cur.idx())->getStatus(cur, cmd, status);
4919         }
4920
4921         // disable in non-fixed-width cells
4922         case LFUN_PARAGRAPH_BREAK:
4923                 // multirow does not allow paragraph breaks
4924                 if (tabular.isMultiRow(cur.idx())) {
4925                         status.setEnabled(false);
4926                         return true;
4927                 }
4928         case LFUN_NEWLINE_INSERT: {
4929                 if (tabular.getPWidth(cur.idx()).zero()) {
4930                         status.setEnabled(false);
4931                         return true;
4932                 } else
4933                         return cell(cur.idx())->getStatus(cur, cmd, status);
4934         }
4935
4936         case LFUN_NEWPAGE_INSERT:
4937                 status.setEnabled(false);
4938                 return true;
4939
4940         case LFUN_PASTE:
4941                 if (tabularStackDirty() && theClipboard().isInternal()) {
4942                         if (cur.selIsMultiCell()) {
4943                                 row_type rs, re;
4944                                 col_type cs, ce;
4945                                 getSelection(cur, rs, re, cs, ce);
4946                                 if (paste_tabular && paste_tabular->ncols() == ce - cs + 1
4947                                           && paste_tabular->nrows() == re - rs + 1)
4948                                         status.setEnabled(true);        
4949                                 else {
4950                                         status.setEnabled(false);
4951                                         status.message(_("Selection size should match clipboard content."));
4952                                 }
4953                         } else
4954                                 status.setEnabled(true);
4955                         return true;
4956                 }
4957                 return cell(cur.idx())->getStatus(cur, cmd, status);
4958
4959         case LFUN_INSET_SETTINGS:
4960                 // relay this lfun to Inset, not to the cell.
4961                 return Inset::getStatus(cur, cmd, status);
4962
4963         default:
4964                 // we try to handle this event in the insets dispatch function.
4965                 return cell(cur.idx())->getStatus(cur, cmd, status);
4966         }
4967         return false;
4968 }
4969
4970
4971 Inset::DisplayType InsetTabular::display() const
4972 {
4973                 if (tabular.is_long_tabular) {
4974                         switch (tabular.longtabular_alignment) {
4975                         case Tabular::LYX_LONGTABULAR_ALIGN_LEFT:
4976                                 return AlignLeft;
4977                         case Tabular::LYX_LONGTABULAR_ALIGN_CENTER:
4978                                 return AlignCenter;
4979                         case Tabular::LYX_LONGTABULAR_ALIGN_RIGHT:
4980                                 return AlignRight;
4981                         default:
4982                                 return AlignCenter;
4983                         }
4984                 } else
4985                         return Inline;
4986 }
4987
4988
4989 void InsetTabular::latex(otexstream & os, OutputParams const & runparams) const
4990 {
4991         tabular.latex(os, runparams);
4992 }
4993
4994
4995 int InsetTabular::plaintext(odocstringstream & os,
4996         OutputParams const & runparams, size_t max_length) const
4997 {
4998         os << '\n'; // output table on a new line
4999         int const dp = runparams.linelen > 0 ? runparams.depth : 0;
5000         tabular.plaintext(os, runparams, dp, false, 0, max_length);
5001         return PLAINTEXT_NEWLINE;
5002 }
5003
5004
5005 int InsetTabular::docbook(odocstream & os, OutputParams const & runparams) const
5006 {
5007         int ret = 0;
5008         Inset * master = 0;
5009
5010         // FIXME: Why not pass a proper DocIterator here?
5011 #if 0
5012         // if the table is inside a float it doesn't need the informaltable
5013         // wrapper. Search for it.
5014         for (master = owner(); master; master = master->owner())
5015                 if (master->lyxCode() == FLOAT_CODE)
5016                         break;
5017 #endif
5018
5019         if (!master) {
5020                 os << "<informaltable>";
5021                 ++ret;
5022         }
5023         ret += tabular.docbook(os, runparams);
5024         if (!master) {
5025                 os << "</informaltable>";
5026                 ++ret;
5027         }
5028         return ret;
5029 }
5030
5031
5032 docstring InsetTabular::xhtml(XHTMLStream & xs, OutputParams const & rp) const
5033 {
5034         return tabular.xhtml(xs, rp);
5035 }
5036
5037
5038 void InsetTabular::validate(LaTeXFeatures & features) const
5039 {
5040         tabular.validate(features);
5041         // FIXME XHTML
5042         // It'd be better to be able to get this from an InsetLayout, but at present
5043         // InsetLayouts do not seem really to work for things that aren't InsetTexts.
5044         if (features.runparams().flavor == OutputParams::HTML)
5045                 features.addCSSSnippet(
5046                         "table { border: 1px solid black; display: inline-block; }\n"
5047                         "td { border: 1px solid black; padding: 0.5ex; }");
5048 }
5049
5050
5051 shared_ptr<InsetTableCell const> InsetTabular::cell(idx_type idx) const
5052 {
5053         return tabular.cellInset(idx);
5054 }
5055
5056
5057 shared_ptr<InsetTableCell> InsetTabular::cell(idx_type idx)
5058 {
5059         return tabular.cellInset(idx);
5060 }
5061
5062
5063 void InsetTabular::cursorPos(BufferView const & bv,
5064                 CursorSlice const & sl, bool boundary, int & x, int & y) const
5065 {
5066         cell(sl.idx())->cursorPos(bv, sl, boundary, x, y);
5067
5068         // y offset     correction
5069         y += cellYPos(sl.idx());
5070         y += tabular.textVOffset(sl.idx());
5071         y += offset_valign_;
5072
5073         // x offset correction
5074         x += cellXPos(sl.idx());
5075         x += tabular.textHOffset(sl.idx());
5076         x += ADD_TO_TABULAR_WIDTH;
5077         x += scx_;
5078 }
5079
5080
5081 int InsetTabular::dist(BufferView & bv, idx_type const cell, int x, int y) const
5082 {
5083         int xx = 0;
5084         int yy = 0;
5085         Inset const & inset = *tabular.cellInset(cell);
5086         Point o = bv.coordCache().getInsets().xy(&inset);
5087         int const xbeg = o.x_ - tabular.textHOffset(cell);
5088         int const xend = xbeg + tabular.cellWidth(cell);
5089         row_type const row = tabular.cellRow(cell);
5090         int const ybeg = o.y_ - tabular.rowAscent(row)
5091                 - tabular.interRowSpace(row) - tabular.textVOffset(cell);
5092         int const yend = ybeg + tabular.cellHeight(cell);
5093
5094         if (x < xbeg)
5095                 xx = xbeg - x;
5096         else if (x > xend)
5097                 xx = x - xend;
5098
5099         if (y < ybeg)
5100                 yy = ybeg - y;
5101         else if (y > yend)
5102                 yy = y - yend;
5103
5104         //lyxerr << " xbeg=" << xbeg << "  xend=" << xend
5105         //       << " ybeg=" << ybeg << " yend=" << yend
5106         //       << " xx=" << xx << " yy=" << yy
5107         //       << " dist=" << xx + yy << endl;
5108         return xx + yy;
5109 }
5110
5111
5112 Inset * InsetTabular::editXY(Cursor & cur, int x, int y)
5113 {
5114         //lyxerr << "InsetTabular::editXY: " << this << endl;
5115         cur.setSelection(false);
5116         cur.push(*this);
5117         cur.idx() = getNearestCell(cur.bv(), x, y);
5118         resetPos(cur);
5119         return cur.bv().textMetrics(&cell(cur.idx())->text()).editXY(cur, x, y);
5120 }
5121
5122
5123 void InsetTabular::setCursorFromCoordinates(Cursor & cur, int x, int y) const
5124 {
5125         cur.idx() = getNearestCell(cur.bv(), x, y);
5126         cur.bv().textMetrics(&cell(cur.idx())->text()).setCursorFromCoordinates(cur, x, y);
5127 }
5128
5129
5130 InsetTabular::idx_type InsetTabular::getNearestCell(BufferView & bv, int x, int y) const
5131 {
5132         idx_type idx_min = 0;
5133         int dist_min = numeric_limits<int>::max();
5134         for (idx_type i = 0, n = nargs(); i != n; ++i) {
5135                 if (bv.coordCache().getInsets().has(tabular.cellInset(i).get())) {
5136                         int const d = dist(bv, i, x, y);
5137                         if (d < dist_min) {
5138                                 dist_min = d;
5139                                 idx_min = i;
5140                         }
5141                 }
5142         }
5143         return idx_min;
5144 }
5145
5146
5147 int InsetTabular::cellYPos(idx_type const cell) const
5148 {
5149         row_type row = tabular.cellRow(cell);
5150         int ly = 0;
5151         for (row_type r = 0; r < row; ++r)
5152                 ly += tabular.rowDescent(r) + tabular.rowAscent(r + 1) 
5153                         + tabular.interRowSpace(r + 1);
5154         return ly;
5155 }
5156
5157
5158 int InsetTabular::cellXPos(idx_type const cell) const
5159 {
5160         col_type col = tabular.cellColumn(cell);
5161         int lx = 0;
5162         for (col_type c = 0; c < col; ++c)
5163                 lx += tabular.column_info[c].width;
5164         return lx;
5165 }
5166
5167
5168 void InsetTabular::resetPos(Cursor & cur) const
5169 {
5170         BufferView & bv = cur.bv();
5171         int const maxwidth = bv.workWidth();
5172
5173         int const scx_old = scx_;
5174         int const i = cur.find(this);
5175         if (i == -1) {
5176                 scx_ = 0;
5177         } else {
5178                 int const X1 = 0;
5179                 int const X2 = maxwidth;
5180                 int const offset = ADD_TO_TABULAR_WIDTH + 2;
5181                 int const x1 = xo(cur.bv()) + cellXPos(cur[i].idx()) + offset;
5182                 int const x2 = x1 + tabular.cellWidth(cur[i].idx());
5183
5184                 if (x1 < X1)
5185                         scx_ = X1 + 20 - x1;
5186                 else if (x2 > X2)
5187                         scx_ = X2 - 20 - x2;
5188                 else
5189                         scx_ = 0;
5190         }
5191
5192         // only update if offset changed
5193         if (scx_ != scx_old)
5194                 cur.screenUpdateFlags(Update::Force | Update::FitCursor);
5195 }
5196
5197
5198 void InsetTabular::moveNextCell(Cursor & cur, EntryDirection entry_from)
5199 {
5200         row_type const row = tabular.cellRow(cur.idx());
5201         col_type const col = tabular.cellColumn(cur.idx());
5202
5203         if (isRightToLeft(cur)) {
5204                 if (tabular.cellColumn(cur.idx()) == 0) {
5205                         if (row == tabular.nrows() - 1)
5206                                 return;
5207                         cur.idx() = tabular.cellBelow(tabular.getLastCellInRow(row));
5208                 } else {
5209                         if (cur.idx() == 0)
5210                                 return;
5211                         if (col == 0)
5212                                 cur.idx() = tabular.getLastCellInRow(row - 1);
5213                         else
5214                                 cur.idx() = tabular.cellIndex(row, col - 1);
5215                 }
5216         } else {
5217                 if (tabular.isLastCell(cur.idx()))
5218                         return;
5219                 if (cur.idx() == tabular.getLastCellInRow(row))
5220                         cur.idx() = tabular.cellIndex(row + 1, 0);
5221                 else {
5222                         col_type const colnextcell = col + tabular.columnSpan(cur.idx());
5223                         cur.idx() = tabular.cellIndex(row, colnextcell);
5224                 }
5225         }
5226
5227         cur.boundary(false);
5228
5229         if (cur.selIsMultiCell()) {
5230                 cur.pit() = cur.lastpit();
5231                 cur.pos() = cur.lastpos();
5232                 resetPos(cur);
5233                 return;
5234         }
5235
5236         cur.pit() = 0;
5237         cur.pos() = 0;
5238
5239         // in visual mode, place cursor at extreme left or right
5240         
5241         switch(entry_from) {
5242
5243         case ENTRY_DIRECTION_RIGHT:
5244                 cur.posVisToRowExtremity(false /* !left */);
5245                 break;
5246         case ENTRY_DIRECTION_LEFT:
5247                 cur.posVisToRowExtremity(true /* left */);
5248                 break;
5249         case ENTRY_DIRECTION_IGNORE:
5250                 // nothing to do in this case
5251                 break;
5252
5253         }
5254         cur.setCurrentFont();
5255         resetPos(cur);
5256 }
5257
5258
5259 void InsetTabular::movePrevCell(Cursor & cur, EntryDirection entry_from)
5260 {
5261         row_type const row = tabular.cellRow(cur.idx());
5262         col_type const col = tabular.cellColumn(cur.idx());
5263
5264         if (isRightToLeft(cur)) {
5265                 if (cur.idx() == tabular.getLastCellInRow(row)) {
5266                         if (row == 0)
5267                                 return;
5268                         cur.idx() = tabular.getFirstCellInRow(row);
5269                         cur.idx() = tabular.cellAbove(cur.idx());
5270                 } else {
5271                         if (tabular.isLastCell(cur.idx()))
5272                                 return;
5273                         if (cur.idx() == tabular.getLastCellInRow(row))
5274                                 cur.idx() = tabular.cellIndex(row + 1, 0);
5275                         else
5276                                 cur.idx() = tabular.cellIndex(row, col + 1);
5277                 }
5278         } else {
5279                 if (cur.idx() == 0) // first cell
5280                         return;
5281                 if (col == 0)
5282                         cur.idx() = tabular.getLastCellInRow(row - 1);
5283                 else
5284                         cur.idx() = tabular.cellIndex(row, col - 1);
5285         }
5286
5287         if (cur.selIsMultiCell()) {
5288                 cur.pit() = cur.lastpit();
5289                 cur.pos() = cur.lastpos();
5290                 resetPos(cur);
5291                 return;
5292         }
5293
5294         cur.pit() = cur.lastpit();
5295         cur.pos() = cur.lastpos();
5296
5297         // in visual mode, place cursor at extreme left or right
5298         
5299         switch(entry_from) {
5300
5301         case ENTRY_DIRECTION_RIGHT:
5302                 cur.posVisToRowExtremity(false /* !left */);
5303                 break;
5304         case ENTRY_DIRECTION_LEFT:
5305                 cur.posVisToRowExtremity(true /* left */);
5306                 break;
5307         case ENTRY_DIRECTION_IGNORE:
5308                 // nothing to do in this case
5309                 break;
5310
5311         }
5312         cur.setCurrentFont();
5313         resetPos(cur);
5314 }
5315
5316
5317 bool InsetTabular::tabularFeatures(Cursor & cur, string const & argument)
5318 {
5319         istringstream is(argument);
5320         string s;
5321         is >> s;
5322         if (insetCode(s) != TABULAR_CODE)
5323                 return false;
5324
5325         // Safe guard.
5326         size_t safe_guard = 0;
5327         for (;;) {
5328                 if (is.eof())
5329                         break;
5330                 safe_guard++;
5331                 if (safe_guard > 1000) {
5332                         LYXERR0("parameter max count reached!");
5333                         break;
5334                 }
5335                 is >> s;
5336                 Tabular::Feature action = Tabular::LAST_ACTION;
5337
5338                 size_t i = 0;
5339                 for (; tabularFeature[i].action != Tabular::LAST_ACTION; ++i) {
5340                         if (s != tabularFeature[i].feature)
5341                                 continue;
5342                         action = tabularFeature[i].action;
5343                         break;
5344                 }
5345                 if (action == Tabular::LAST_ACTION) {
5346                         LYXERR0("Feature not found " << s);
5347                         continue;
5348                 }
5349                 string val;
5350                 if (tabularFeature[i].need_value)
5351                         is >> val;
5352                 LYXERR(Debug::DEBUG, "Feature: " << s << "\t\tvalue: " << val);
5353                 tabularFeatures(cur, action, val);
5354         }
5355         return true;
5356 }
5357
5358
5359 static void checkLongtableSpecial(Tabular::ltType & ltt,
5360                           string const & special, bool & flag)
5361 {
5362         if (special == "dl_above") {
5363                 ltt.topDL = flag;
5364                 ltt.set = false;
5365         } else if (special == "dl_below") {
5366                 ltt.bottomDL = flag;
5367                 ltt.set = false;
5368         } else if (special == "empty") {
5369                 ltt.empty = flag;
5370                 ltt.set = false;
5371         } else if (flag) {
5372                 ltt.empty = false;
5373                 ltt.set = true;
5374         }
5375 }
5376
5377
5378 bool InsetTabular::oneCellHasRotationState(bool rotated,
5379                 row_type row_start, row_type row_end,
5380                 col_type col_start, col_type col_end) const 
5381 {
5382         for (row_type r = row_start; r <= row_end; ++r)
5383                 for (col_type c = col_start; c <= col_end; ++c)
5384                         if (rotated) {
5385                                 if (tabular.getRotateCell(tabular.cellIndex(r, c)) != 0)
5386                                         return true;
5387                         } else {
5388                                 if (tabular.getRotateCell(tabular.cellIndex(r, c)) == 0)
5389                                         return true;
5390                         }
5391         return false;
5392 }
5393
5394
5395 void InsetTabular::tabularFeatures(Cursor & cur,
5396         Tabular::Feature feature, string const & value)
5397 {
5398         col_type sel_col_start;
5399         col_type sel_col_end;
5400         row_type sel_row_start;
5401         row_type sel_row_end;
5402         bool setLines = false;
5403         LyXAlignment setAlign = LYX_ALIGN_LEFT;
5404         Tabular::VAlignment setVAlign = Tabular::LYX_VALIGN_TOP;
5405
5406         switch (feature) {
5407
5408         case Tabular::M_ALIGN_LEFT:
5409         case Tabular::ALIGN_LEFT:
5410                 setAlign = LYX_ALIGN_LEFT;
5411                 break;
5412
5413         case Tabular::M_ALIGN_RIGHT:
5414         case Tabular::ALIGN_RIGHT:
5415                 setAlign = LYX_ALIGN_RIGHT;
5416                 break;
5417
5418         case Tabular::M_ALIGN_CENTER:
5419         case Tabular::ALIGN_CENTER:
5420                 setAlign = LYX_ALIGN_CENTER;
5421                 break;
5422
5423         case Tabular::ALIGN_BLOCK:
5424                 setAlign = LYX_ALIGN_BLOCK;
5425                 break;
5426
5427         case Tabular::ALIGN_DECIMAL:
5428                 if (tabular.column_info[tabular.cellColumn(cur.idx())].alignment == LYX_ALIGN_DECIMAL)
5429                         setAlign = LYX_ALIGN_CENTER;
5430                 else
5431                         setAlign = LYX_ALIGN_DECIMAL;
5432                 break;
5433
5434         case Tabular::M_VALIGN_TOP:
5435         case Tabular::VALIGN_TOP:
5436                 setVAlign = Tabular::LYX_VALIGN_TOP;
5437                 break;
5438
5439         case Tabular::M_VALIGN_BOTTOM:
5440         case Tabular::VALIGN_BOTTOM:
5441                 setVAlign = Tabular::LYX_VALIGN_BOTTOM;
5442                 break;
5443
5444         case Tabular::M_VALIGN_MIDDLE:
5445         case Tabular::VALIGN_MIDDLE:
5446                 setVAlign = Tabular::LYX_VALIGN_MIDDLE;
5447                 break;
5448
5449         default:
5450                 break;
5451         }
5452
5453         cur.recordUndoInset(ATOMIC_UNDO, this);
5454
5455         getSelection(cur, sel_row_start, sel_row_end, sel_col_start, sel_col_end);
5456         row_type const row = tabular.cellRow(cur.idx());
5457         col_type const column = tabular.cellColumn(cur.idx());
5458         bool flag = true;
5459         Tabular::ltType ltt;
5460
5461         switch (feature) {
5462
5463         case Tabular::SET_TABULAR_WIDTH:
5464                 tabular.setTabularWidth(Length(value));
5465                 break;
5466
5467         case Tabular::SET_PWIDTH: {
5468                 Length const len(value);
5469                 tabular.setColumnPWidth(cur, cur.idx(), len);
5470                 if (len.zero()
5471                     && tabular.getAlignment(cur.idx(), true) == LYX_ALIGN_BLOCK)
5472                         tabularFeatures(cur, Tabular::ALIGN_CENTER, string());
5473                 break;
5474         }
5475
5476         case Tabular::SET_MPWIDTH:
5477                 tabular.setMColumnPWidth(cur, cur.idx(), Length(value));
5478                 break;
5479
5480         case Tabular::SET_MROFFSET:
5481                 tabular.setMROffset(cur, cur.idx(), Length(value));
5482                 break;
5483
5484         case Tabular::SET_SPECIAL_COLUMN:
5485         case Tabular::SET_SPECIAL_MULTICOLUMN:
5486                 if (value == "none")
5487                         tabular.setAlignSpecial(cur.idx(), docstring(), feature);
5488                 else
5489                         tabular.setAlignSpecial(cur.idx(), from_utf8(value), feature);
5490                 break;
5491
5492         case Tabular::APPEND_ROW:
5493                 // append the row into the tabular
5494                 tabular.appendRow(row);
5495                 break;
5496
5497         case Tabular::APPEND_COLUMN:
5498                 // append the column into the tabular
5499                 tabular.appendColumn(column);
5500                 cur.idx() = tabular.cellIndex(row, column);
5501                 break;
5502
5503         case Tabular::DELETE_ROW:
5504                 if (sel_row_end == tabular.nrows() - 1 && sel_row_start != 0) {
5505                         for (col_type c = 0; c < tabular.ncols(); c++)
5506                                 tabular.setBottomLine(tabular.cellIndex(sel_row_start - 1, c),
5507                                         tabular.bottomLine(tabular.cellIndex(sel_row_end, c)));
5508                 }
5509
5510                 for (row_type r = sel_row_start; r <= sel_row_end; ++r)
5511                         tabular.deleteRow(sel_row_start);
5512                 if (sel_row_start >= tabular.nrows())
5513                         --sel_row_start;
5514                 cur.idx() = tabular.cellIndex(sel_row_start, column);
5515                 cur.pit() = 0;
5516                 cur.pos() = 0;
5517                 cur.setSelection(false);
5518                 break;
5519
5520         case Tabular::DELETE_COLUMN:
5521                 if (sel_col_end == tabular.ncols() - 1 && sel_col_start != 0) {
5522                         for (row_type r = 0; r < tabular.nrows(); r++)
5523                                 tabular.setRightLine(tabular.cellIndex(r, sel_col_start - 1),
5524                                         tabular.rightLine(tabular.cellIndex(r, sel_col_end)));
5525                 }
5526
5527                 if (sel_col_start == 0 && sel_col_end != tabular.ncols() - 1) {
5528                         for (row_type r = 0; r < tabular.nrows(); r++)
5529                                 tabular.setLeftLine(tabular.cellIndex(r, sel_col_end + 1),
5530                                         tabular.leftLine(tabular.cellIndex(r, 0)));
5531                 }
5532
5533                 for (col_type c = sel_col_start; c <= sel_col_end; ++c)
5534                         tabular.deleteColumn(sel_col_start);
5535                 if (sel_col_start >= tabular.ncols())
5536                         --sel_col_start;
5537                 cur.idx() = tabular.cellIndex(row, sel_col_start);
5538                 cur.pit() = 0;
5539                 cur.pos() = 0;
5540                 cur.setSelection(false);
5541                 break;
5542
5543         case Tabular::COPY_ROW:
5544                 tabular.copyRow(row);
5545                 break;
5546
5547         case Tabular::COPY_COLUMN:
5548                 tabular.copyColumn(column);
5549                 cur.idx() = tabular.cellIndex(row, column);
5550                 break;
5551
5552         case Tabular::MOVE_COLUMN_RIGHT:
5553                 tabular.moveColumn(column, Tabular::RIGHT);
5554                 cur.idx() = tabular.cellIndex(row, column + 1);
5555                 break;
5556
5557         case Tabular::MOVE_COLUMN_LEFT:
5558                 tabular.moveColumn(column, Tabular::LEFT);
5559                 cur.idx() = tabular.cellIndex(row, column - 1);
5560                 break;
5561
5562         case Tabular::MOVE_ROW_DOWN:
5563                 tabular.moveRow(row, Tabular::DOWN);
5564                 cur.idx() = tabular.cellIndex(row + 1, column);
5565                 break;
5566
5567         case Tabular::MOVE_ROW_UP:
5568                 tabular.moveRow(row, Tabular::UP);
5569                 cur.idx() = tabular.cellIndex(row - 1, column);
5570                 break;
5571
5572         case Tabular::SET_LINE_TOP:
5573         case Tabular::TOGGLE_LINE_TOP: {
5574                 bool lineSet = (feature == Tabular::SET_LINE_TOP)
5575                                ? (value == "true") : !tabular.topLine(cur.idx());
5576                 for (row_type r = sel_row_start; r <= sel_row_end; ++r)
5577                         for (col_type c = sel_col_start; c <= sel_col_end; ++c)
5578                                 tabular.setTopLine(tabular.cellIndex(r, c), lineSet);
5579                 break;
5580         }
5581
5582         case Tabular::SET_LINE_BOTTOM:
5583         case Tabular::TOGGLE_LINE_BOTTOM: {
5584                 bool lineSet = (feature == Tabular::SET_LINE_BOTTOM)
5585                                ? (value == "true") : !tabular.bottomLine(cur.idx());
5586                 for (row_type r = sel_row_start; r <= sel_row_end; ++r)
5587                         for (col_type c = sel_col_start; c <= sel_col_end; ++c)
5588                                 tabular.setBottomLine(tabular.cellIndex(r, c), lineSet);
5589                 break;
5590         }
5591
5592         case Tabular::SET_LINE_LEFT:
5593         case Tabular::TOGGLE_LINE_LEFT: {
5594                 bool lineSet = (feature == Tabular::SET_LINE_LEFT)
5595                                ? (value == "true") : !tabular.leftLine(cur.idx());
5596                 for (row_type r = sel_row_start; r <= sel_row_end; ++r)
5597                         for (col_type c = sel_col_start; c <= sel_col_end; ++c)
5598                                 tabular.setLeftLine(tabular.cellIndex(r, c), lineSet);
5599                 break;
5600         }
5601
5602         case Tabular::SET_LINE_RIGHT:
5603         case Tabular::TOGGLE_LINE_RIGHT: {
5604                 bool lineSet = (feature == Tabular::SET_LINE_RIGHT)
5605                                ? (value == "true") : !tabular.rightLine(cur.idx());
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.setRightLine(tabular.cellIndex(r, c), lineSet);
5609                 break;
5610         }
5611
5612         case Tabular::M_ALIGN_LEFT:
5613         case Tabular::M_ALIGN_RIGHT:
5614         case Tabular::M_ALIGN_CENTER:
5615         case Tabular::ALIGN_LEFT:
5616         case Tabular::ALIGN_RIGHT:
5617         case Tabular::ALIGN_CENTER:
5618         case Tabular::ALIGN_BLOCK:
5619         case Tabular::ALIGN_DECIMAL:
5620                 for (row_type r = sel_row_start; r <= sel_row_end; ++r)
5621                         for (col_type c = sel_col_start; c <= sel_col_end; ++c)
5622                                 tabular.setAlignment(tabular.cellIndex(r, c), setAlign,
5623                                 !tabular.getPWidth(c).zero());
5624                 break;
5625
5626         case Tabular::M_VALIGN_TOP:
5627         case Tabular::M_VALIGN_BOTTOM:
5628         case Tabular::M_VALIGN_MIDDLE:
5629                 flag = false;
5630         case Tabular::VALIGN_TOP:
5631         case Tabular::VALIGN_BOTTOM:
5632         case Tabular::VALIGN_MIDDLE:
5633                 for (row_type r = sel_row_start; r <= sel_row_end; ++r)
5634                         for (col_type c = sel_col_start; c <= sel_col_end; ++c)
5635                                 tabular.setVAlignment(tabular.cellIndex(r, c), setVAlign, flag);
5636                 break;
5637
5638         case Tabular::SET_MULTICOLUMN: {
5639                 if (!cur.selection()) {
5640                         // just multicol for one single cell
5641                         // check whether we are completely in a multicol
5642                         if (!tabular.isMultiColumn(cur.idx()))
5643                                 tabular.setMultiColumn(cur.idx(), 1,
5644                                         tabular.rightLine(cur.idx()));
5645                         break;
5646                 }
5647                 // we have a selection so this means we just add all these
5648                 // cells to form a multicolumn cell
5649                 idx_type const s_start = cur.selBegin().idx();
5650                 row_type const col_start = tabular.cellColumn(s_start);
5651                 row_type const col_end = tabular.cellColumn(cur.selEnd().idx());
5652                 cur.idx() = tabular.setMultiColumn(s_start, col_end - col_start + 1,
5653                                                    tabular.rightLine(cur.selEnd().idx()));
5654                 cur.pit() = 0;
5655                 cur.pos() = 0;
5656                 cur.setSelection(false);
5657                 break;
5658         }
5659
5660         case Tabular::UNSET_MULTICOLUMN: {
5661                 if (!cur.selection()) {
5662                         if (tabular.isMultiColumn(cur.idx()))
5663                                 tabular.unsetMultiColumn(cur.idx());
5664                 }
5665                 break;
5666         }
5667
5668         case Tabular::MULTICOLUMN: {
5669                 if (!cur.selection()) {
5670                         if (tabular.isMultiColumn(cur.idx()))
5671                                 tabularFeatures(cur, Tabular::UNSET_MULTICOLUMN);
5672                         else
5673                                 tabularFeatures(cur, Tabular::SET_MULTICOLUMN);
5674                         break;
5675                 }
5676                 bool merge = false;
5677                 for (col_type c = sel_col_start; c <= sel_col_end; ++c) {
5678                         row_type const r = sel_row_start;
5679                         if (!tabular.isMultiColumn(tabular.cellIndex(r, c))
5680                             || (r > sel_row_start && !tabular.isPartOfMultiColumn(r, c)))
5681                                 merge = true;
5682                 }
5683                 // If the selection contains at least one singlecol cell
5684                 // or multiple multicol cells,
5685                 // we assume the user will merge is to a single multicol
5686                 if (merge)
5687                         tabularFeatures(cur, Tabular::SET_MULTICOLUMN);
5688                 else
5689                         tabularFeatures(cur, Tabular::UNSET_MULTICOLUMN);
5690                 break;
5691         }
5692
5693         case Tabular::SET_MULTIROW: {
5694                 if (!cur.selection()) {
5695                         // just multirow for one single cell
5696                         // check whether we are completely in a multirow
5697                         if (!tabular.isMultiRow(cur.idx()))
5698                                 tabular.setMultiRow(cur.idx(), 1,
5699                                                     tabular.bottomLine(cur.idx()));
5700                         break;
5701                 }
5702                 // we have a selection so this means we just add all this
5703                 // cells to form a multirow cell
5704                 idx_type const s_start = cur.selBegin().idx();
5705                 row_type const row_start = tabular.cellRow(s_start);
5706                 row_type const row_end = tabular.cellRow(cur.selEnd().idx());
5707                 cur.idx() = tabular.setMultiRow(s_start, row_end - row_start + 1,
5708                                                 tabular.bottomLine(cur.selEnd().idx()));
5709                 cur.pit() = 0;
5710                 cur.pos() = 0;
5711                 cur.setSelection(false);
5712                 break;
5713         }
5714
5715         case Tabular::UNSET_MULTIROW: {
5716                 if (!cur.selection()) {
5717                         if (tabular.isMultiRow(cur.idx()))
5718                                 tabular.unsetMultiRow(cur.idx());
5719                 }
5720                 break;
5721         }
5722
5723         case Tabular::MULTIROW: {
5724                 if (!cur.selection()) {
5725                         if (tabular.isMultiRow(cur.idx()))
5726                                 tabularFeatures(cur, Tabular::UNSET_MULTIROW);
5727                         else
5728                                 tabularFeatures(cur, Tabular::SET_MULTIROW);
5729                         break;
5730                 }
5731                 bool merge = false;
5732                 for (row_type r = sel_row_start; r <= sel_row_end; ++r) {
5733                         col_type const c = sel_col_start;
5734                         if (!tabular.isMultiRow(tabular.cellIndex(r, c))
5735                             || (r > sel_row_start && !tabular.isPartOfMultiRow(r, c)))
5736                                 merge = true;
5737                 }
5738                 // If the selection contains at least one singlerow cell
5739                 // or multiple multirow cells,
5740                 // we assume the user will merge is to a single multirow
5741                 if (merge)
5742                         tabularFeatures(cur, Tabular::SET_MULTIROW);
5743                 else
5744                         tabularFeatures(cur, Tabular::UNSET_MULTIROW);
5745                 break;
5746         }
5747
5748         case Tabular::SET_ALL_LINES:
5749                 setLines = true;
5750         case Tabular::UNSET_ALL_LINES:
5751                 for (row_type r = sel_row_start; r <= sel_row_end; ++r)
5752                         for (col_type c = sel_col_start; c <= sel_col_end; ++c) {
5753                                 idx_type const cell = tabular.cellIndex(r, c);
5754                                 tabular.setTopLine(cell, setLines);
5755                                 tabular.setBottomLine(cell, setLines);
5756                                 tabular.setRightLine(cell, setLines);
5757                                 tabular.setLeftLine(cell, setLines);
5758                         }
5759                 break;
5760
5761         case Tabular::SET_BORDER_LINES:
5762                 for (row_type r = sel_row_start; r <= sel_row_end; ++r) {
5763                         tabular.setLeftLine(tabular.cellIndex(r, sel_col_start), true);
5764                         tabular.setRightLine(tabular.cellIndex(r, sel_col_end), true);
5765                 }
5766                 for (col_type c = sel_col_start; c <= sel_col_end; ++c) {
5767                         tabular.setTopLine(tabular.cellIndex(sel_row_start, c), true);
5768                         tabular.setBottomLine(tabular.cellIndex(sel_row_end, c), true);
5769                 }
5770                 break;
5771
5772         case Tabular::SET_LONGTABULAR:
5773                 tabular.is_long_tabular = true;
5774                 break;
5775
5776         case Tabular::UNSET_LONGTABULAR:
5777                 for (row_type r = 0; r < tabular.nrows(); ++r) {
5778                         if (tabular.ltCaption(r)) {
5779                                 cur.idx() = tabular.cellIndex(r, 0);
5780                                 cur.pit() = 0;
5781                                 cur.pos() = 0;
5782                                 tabularFeatures(cur, Tabular::TOGGLE_LTCAPTION);
5783                         }
5784                 }
5785                 tabular.is_long_tabular = false;
5786                 break;
5787
5788         case Tabular::SET_ROTATE_TABULAR:
5789                 tabular.rotate = convert<int>(value);
5790                 break;
5791
5792         case Tabular::UNSET_ROTATE_TABULAR:
5793                 tabular.rotate = 0;
5794                 break;
5795
5796         case Tabular::TOGGLE_ROTATE_TABULAR:
5797                 // when pressing the rotate button we default to 90° rotation
5798                 tabular.rotate != 0 ? tabular.rotate = 0 : tabular.rotate = 90;
5799                 break;
5800
5801         case Tabular::TABULAR_VALIGN_TOP:
5802                 tabular.tabular_valignment = Tabular::LYX_VALIGN_TOP;
5803                 break;
5804
5805         case Tabular::TABULAR_VALIGN_MIDDLE:
5806                 tabular.tabular_valignment = Tabular::LYX_VALIGN_MIDDLE;
5807                 break;
5808
5809         case Tabular::TABULAR_VALIGN_BOTTOM:
5810                 tabular.tabular_valignment = Tabular::LYX_VALIGN_BOTTOM;
5811                 break;
5812
5813         case Tabular::LONGTABULAR_ALIGN_LEFT:
5814                 tabular.longtabular_alignment = Tabular::LYX_LONGTABULAR_ALIGN_LEFT;
5815                 break;
5816
5817         case Tabular::LONGTABULAR_ALIGN_CENTER:
5818                 tabular.longtabular_alignment = Tabular::LYX_LONGTABULAR_ALIGN_CENTER;
5819                 break;
5820
5821         case Tabular::LONGTABULAR_ALIGN_RIGHT:
5822                 tabular.longtabular_alignment = Tabular::LYX_LONGTABULAR_ALIGN_RIGHT;
5823                 break;
5824
5825                 
5826
5827         case Tabular::SET_ROTATE_CELL:
5828                 for (row_type r = sel_row_start; r <= sel_row_end; ++r)
5829                         for (col_type c = sel_col_start; c <= sel_col_end; ++c)
5830                                 tabular.setRotateCell(tabular.cellIndex(r, c), convert<int>(value));
5831                 break;
5832
5833         case Tabular::UNSET_ROTATE_CELL:
5834                 for (row_type r = sel_row_start; r <= sel_row_end; ++r)
5835                         for (col_type c = sel_col_start; c <= sel_col_end; ++c)
5836                                 tabular.setRotateCell(tabular.cellIndex(r, c), 0);
5837                 break;
5838
5839         case Tabular::TOGGLE_ROTATE_CELL:
5840                 {
5841                 bool oneNotRotated = oneCellHasRotationState(false,
5842                         sel_row_start, sel_row_end, sel_col_start, sel_col_end);
5843
5844                 for (row_type r = sel_row_start; r <= sel_row_end; ++r)
5845                         for (col_type c = sel_col_start; c <= sel_col_end; ++c) {
5846                                 // when pressing the rotate cell button we default to 90° rotation
5847                                 if (oneNotRotated)
5848                                         tabular.setRotateCell(tabular.cellIndex(r, c), 90);
5849                                 else
5850                                         tabular.setRotateCell(tabular.cellIndex(r, c), 0);
5851                         }
5852                 }
5853                 break;
5854
5855         case Tabular::SET_USEBOX: {
5856                 Tabular::BoxType val = Tabular::BoxType(convert<int>(value));
5857                 if (val == tabular.getUsebox(cur.idx()))
5858                         val = Tabular::BOX_NONE;
5859                 for (row_type r = sel_row_start; r <= sel_row_end; ++r)
5860                         for (col_type c = sel_col_start; c <= sel_col_end; ++c)
5861                                 tabular.setUsebox(tabular.cellIndex(r, c), val);
5862                 break;
5863         }
5864
5865         case Tabular::UNSET_LTFIRSTHEAD:
5866                 flag = false;
5867         case Tabular::SET_LTFIRSTHEAD:
5868                 tabular.getRowOfLTFirstHead(row, ltt);
5869                 checkLongtableSpecial(ltt, value, flag);
5870                 tabular.setLTHead(row, flag, ltt, true);
5871                 break;
5872
5873         case Tabular::UNSET_LTHEAD:
5874                 flag = false;
5875         case Tabular::SET_LTHEAD:
5876                 tabular.getRowOfLTHead(row, ltt);
5877                 checkLongtableSpecial(ltt, value, flag);
5878                 tabular.setLTHead(row, flag, ltt, false);
5879                 break;
5880
5881         case Tabular::UNSET_LTFOOT:
5882                 flag = false;
5883         case Tabular::SET_LTFOOT:
5884                 tabular.getRowOfLTFoot(row, ltt);
5885                 checkLongtableSpecial(ltt, value, flag);
5886                 tabular.setLTFoot(row, flag, ltt, false);
5887                 break;
5888
5889         case Tabular::UNSET_LTLASTFOOT:
5890                 flag = false;
5891         case Tabular::SET_LTLASTFOOT:
5892                 tabular.getRowOfLTLastFoot(row, ltt);
5893                 checkLongtableSpecial(ltt, value, flag);
5894                 tabular.setLTFoot(row, flag, ltt, true);
5895                 break;
5896
5897         case Tabular::UNSET_LTNEWPAGE:
5898                 flag = false;
5899         case Tabular::SET_LTNEWPAGE:
5900                 tabular.setLTNewPage(row, flag);
5901                 break;
5902
5903         case Tabular::SET_LTCAPTION: {
5904                 if (tabular.ltCaption(row))
5905                         break;
5906                 cur.idx() = tabular.setLTCaption(row, true);
5907                 cur.pit() = 0;
5908                 cur.pos() = 0;
5909                 cur.setSelection(false);
5910                 // If a row is set as caption, then also insert
5911                 // a caption. Otherwise the LaTeX output is broken.
5912                 lyx::dispatch(FuncRequest(LFUN_INSET_SELECT_ALL));
5913                 lyx::dispatch(FuncRequest(LFUN_CAPTION_INSERT));
5914                 break;
5915         }
5916         
5917         case Tabular::UNSET_LTCAPTION: {
5918                 if (!tabular.ltCaption(row))
5919                         break;
5920                 cur.idx() = tabular.setLTCaption(row, false);
5921                 cur.pit() = 0;
5922                 cur.pos() = 0;
5923                 cur.setSelection(false);
5924                 FuncRequest fr(LFUN_INSET_DISSOLVE, "caption");
5925                 if (lyx::getStatus(fr).enabled())
5926                         lyx::dispatch(fr);
5927                 break;
5928         }
5929
5930         case Tabular::TOGGLE_LTCAPTION: {
5931                 if (tabular.ltCaption(row))
5932                         tabularFeatures(cur, Tabular::UNSET_LTCAPTION);
5933                 else
5934                         tabularFeatures(cur, Tabular::SET_LTCAPTION);
5935                 break;
5936         }
5937
5938         case Tabular::SET_BOOKTABS:
5939                 tabular.use_booktabs = true;
5940                 break;
5941
5942         case Tabular::UNSET_BOOKTABS:
5943                 tabular.use_booktabs = false;
5944                 break;
5945
5946         case Tabular::SET_TOP_SPACE: {
5947                 Length len;
5948                 if (value == "default")
5949                         for (row_type r = sel_row_start; r <= sel_row_end; ++r)
5950                                 tabular.row_info[r].top_space_default = true;
5951                 else if (value == "none")
5952                         for (row_type r = sel_row_start; r <= sel_row_end; ++r) {
5953                                 tabular.row_info[r].top_space_default = false;
5954                                 tabular.row_info[r].top_space = len;
5955                         }
5956                 else if (isValidLength(value, &len))
5957                         for (row_type r = sel_row_start; r <= sel_row_end; ++r) {
5958                                 tabular.row_info[r].top_space_default = false;
5959                                 tabular.row_info[r].top_space = len;
5960                         }
5961                 break;
5962         }
5963
5964         case Tabular::SET_BOTTOM_SPACE: {
5965                 Length len;
5966                 if (value == "default")
5967                         for (row_type r = sel_row_start; r <= sel_row_end; ++r)
5968                                 tabular.row_info[r].bottom_space_default = true;
5969                 else if (value == "none")
5970                         for (row_type r = sel_row_start; r <= sel_row_end; ++r) {
5971                                 tabular.row_info[r].bottom_space_default = false;
5972                                 tabular.row_info[r].bottom_space = len;
5973                         }
5974                 else if (isValidLength(value, &len))
5975                         for (row_type r = sel_row_start; r <= sel_row_end; ++r) {
5976                                 tabular.row_info[r].bottom_space_default = false;
5977                                 tabular.row_info[r].bottom_space = len;
5978                         }
5979                 break;
5980         }
5981
5982         case Tabular::SET_INTERLINE_SPACE: {
5983                 Length len;
5984                 if (value == "default")
5985                         for (row_type r = sel_row_start; r <= sel_row_end; ++r)
5986                                 tabular.row_info[r].interline_space_default = true;
5987                 else if (value == "none")
5988                         for (row_type r = sel_row_start; r <= sel_row_end; ++r) {
5989                                 tabular.row_info[r].interline_space_default = false;
5990                                 tabular.row_info[r].interline_space = len;
5991                         }
5992                 else if (isValidLength(value, &len))
5993                         for (row_type r = sel_row_start; r <= sel_row_end; ++r) {
5994                                 tabular.row_info[r].interline_space_default = false;
5995                                 tabular.row_info[r].interline_space = len;
5996                         }
5997                 break;
5998         }
5999
6000         case Tabular::SET_DECIMAL_POINT:
6001                 for (col_type c = sel_col_start; c <= sel_col_end; ++c)
6002                         tabular.column_info[c].decimal_point = from_utf8(value);
6003                 break;
6004
6005         // dummy stuff just to avoid warnings
6006         case Tabular::LAST_ACTION:
6007                 break;
6008         }
6009 }
6010
6011
6012 bool InsetTabular::copySelection(Cursor & cur)
6013 {
6014         if (!cur.selection())
6015                 return false;
6016
6017         row_type rs, re;
6018         col_type cs, ce;
6019         getSelection(cur, rs, re, cs, ce);
6020
6021         paste_tabular.reset(new Tabular(tabular));
6022
6023         for (row_type r = 0; r < rs; ++r)
6024                 paste_tabular->deleteRow(0);
6025
6026         row_type const rows = re - rs + 1;
6027         while (paste_tabular->nrows() > rows)
6028                 paste_tabular->deleteRow(rows);
6029
6030         for (col_type c = 0; c < cs; ++c)
6031                 paste_tabular->deleteColumn(0);
6032
6033         col_type const columns = ce - cs + 1;
6034         while (paste_tabular->ncols() > columns)
6035                 paste_tabular->deleteColumn(columns);
6036
6037         paste_tabular->setBuffer(tabular.buffer());
6038
6039         odocstringstream os;
6040         OutputParams const runparams(0);
6041         paste_tabular->plaintext(os, runparams, 0, true, '\t', INT_MAX);
6042         // Needed for the "Edit->Paste recent" menu and the system clipboard.
6043         cap::copySelection(cur, os.str());
6044
6045         // mark tabular stack dirty
6046         // FIXME: this is a workaround for bug 1919. Should be removed for 1.5,
6047         // when we (hopefully) have a one-for-all paste mechanism.
6048         // This must be called after cap::copySelection.
6049         dirtyTabularStack(true);
6050
6051         return true;
6052 }
6053
6054
6055 bool InsetTabular::pasteClipboard(Cursor & cur)
6056 {
6057         if (!paste_tabular)
6058                 return false;
6059         col_type actcol = tabular.cellColumn(cur.idx());
6060         row_type actrow = tabular.cellRow(cur.idx());
6061
6062         if (cur.selIsMultiCell()) {
6063                 row_type re;
6064                 col_type ce;
6065                 getSelection(cur, actrow, re, actcol, ce);
6066         }
6067
6068         for (row_type r1 = 0, r2 = actrow;
6069              r1 < paste_tabular->nrows() && r2 < tabular.nrows();
6070              ++r1, ++r2) {
6071                 for (col_type c1 = 0, c2 = actcol;
6072                     c1 < paste_tabular->ncols() && c2 < tabular.ncols();
6073                     ++c1, ++c2) {
6074                         if (paste_tabular->isPartOfMultiColumn(r1, c1) &&
6075                               tabular.isPartOfMultiColumn(r2, c2))
6076                                 continue;
6077                         if (paste_tabular->isPartOfMultiColumn(r1, c1)) {
6078                                 --c2;
6079                                 continue;
6080                         }
6081                         if (tabular.isPartOfMultiColumn(r2, c2)) {
6082                                 --c1;
6083                                 continue;
6084                         }
6085                         shared_ptr<InsetTableCell> inset(
6086                                 new InsetTableCell(*paste_tabular->cellInset(r1, c1)));
6087                         tabular.setCellInset(r2, c2, inset);
6088                         // FIXME?: why do we need to do this explicitly? (EL)
6089                         tabular.cellInset(r2, c2)->setBuffer(tabular.buffer());
6090
6091                         // FIXME: change tracking (MG)
6092                         inset->setChange(Change(buffer().params().trackChanges ?
6093                                                 Change::INSERTED : Change::UNCHANGED));
6094                         cur.pos() = 0;
6095                 }
6096         }
6097         return true;
6098 }
6099
6100
6101 void InsetTabular::cutSelection(Cursor & cur)
6102 {
6103         if (!cur.selection())
6104                 return;
6105
6106         row_type rs, re;
6107         col_type cs, ce;
6108         getSelection(cur, rs, re, cs, ce);
6109         for (row_type r = rs; r <= re; ++r) {
6110                 for (col_type c = cs; c <= ce; ++c) {
6111                         shared_ptr<InsetTableCell> t
6112                                 = cell(tabular.cellIndex(r, c));
6113                         if (buffer().params().trackChanges)
6114                                 // FIXME: Change tracking (MG)
6115                                 t->setChange(Change(Change::DELETED));
6116                         else
6117                                 t->clear();
6118                 }
6119         }
6120
6121         // cursor position might be invalid now
6122         if (cur.pit() > cur.lastpit())
6123                 cur.pit() = cur.lastpit();
6124         if (cur.pos() > cur.lastpos())
6125                 cur.pos() = cur.lastpos();
6126         cur.clearSelection();
6127 }
6128
6129
6130 bool InsetTabular::isRightToLeft(Cursor & cur) const
6131 {
6132         // LASSERT: It might be better to abandon this Buffer.
6133         LASSERT(cur.depth() > 1, return false);
6134         Paragraph const & parentpar = cur[cur.depth() - 2].paragraph();
6135         pos_type const parentpos = cur[cur.depth() - 2].pos();
6136         return parentpar.getFontSettings(buffer().params(),
6137                                          parentpos).language()->rightToLeft();
6138 }
6139
6140
6141 docstring InsetTabular::asString(idx_type stidx, idx_type enidx, 
6142                                  bool intoInsets)
6143 {
6144         LASSERT(stidx <= enidx, return docstring());
6145         docstring retval;
6146         col_type const col1 = tabular.cellColumn(stidx);
6147         col_type const col2 = tabular.cellColumn(enidx);
6148         row_type const row1 = tabular.cellRow(stidx);
6149         row_type const row2 = tabular.cellRow(enidx);
6150         bool first = true;
6151         for (col_type col = col1; col <= col2; col++)
6152                 for (row_type row = row1; row <= row2; row++) {
6153                         if (!first)
6154                                 retval += "\n";
6155                         else
6156                                 first = false;
6157                         retval += tabular.cellInset(row, col)->asString(intoInsets);
6158                 }
6159         return retval;
6160 }
6161
6162
6163 void InsetTabular::getSelection(Cursor & cur,
6164         row_type & rs, row_type & re, col_type & cs, col_type & ce) const
6165 {
6166         CursorSlice const & beg = cur.selBegin();
6167         CursorSlice const & end = cur.selEnd();
6168         cs = tabular.cellColumn(beg.idx());
6169         ce = tabular.cellColumn(end.idx());
6170         if (cs > ce)
6171                 swap(cs, ce);
6172
6173         rs = tabular.cellRow(beg.idx());
6174         re = tabular.cellRow(end.idx());
6175         if (rs > re)
6176                 swap(rs, re);
6177 }
6178
6179
6180 Text * InsetTabular::getText(int idx) const
6181 {
6182         return size_t(idx) < nargs() ? cell(idx)->getText(0) : 0;
6183 }
6184
6185
6186 void InsetTabular::setChange(Change const & change)
6187 {
6188         for (idx_type idx = 0; idx < nargs(); ++idx)
6189                 cell(idx)->setChange(change);
6190 }
6191
6192
6193 void InsetTabular::acceptChanges()
6194 {
6195         for (idx_type idx = 0; idx < nargs(); ++idx)
6196                 cell(idx)->acceptChanges();
6197 }
6198
6199
6200 void InsetTabular::rejectChanges()
6201 {
6202         for (idx_type idx = 0; idx < nargs(); ++idx)
6203                 cell(idx)->rejectChanges();
6204 }
6205
6206
6207 bool InsetTabular::allowParagraphCustomization(idx_type cell) const
6208 {
6209         return tabular.getPWidth(cell).zero();
6210 }
6211
6212
6213 bool InsetTabular::forcePlainLayout(idx_type cell) const
6214 {
6215         return !tabular.getPWidth(cell).zero();
6216 }
6217
6218
6219 bool InsetTabular::insertPlaintextString(BufferView & bv, docstring const & buf,
6220                                      bool usePaste)
6221 {
6222         if (buf.length() <= 0)
6223                 return true;
6224
6225         col_type cols = 1;
6226         row_type rows = 1;
6227         col_type maxCols = 1;
6228         size_t const len = buf.length();
6229         size_t p = 0;
6230
6231         while (p < len &&
6232                (p = buf.find_first_of(from_ascii("\t\n"), p)) != docstring::npos) {
6233                 switch (buf[p]) {
6234                 case '\t':
6235                         ++cols;
6236                         break;
6237                 case '\n':
6238                         if (p + 1 < len)
6239                                 ++rows;
6240                         maxCols = max(cols, maxCols);
6241                         cols = 1;
6242                         break;
6243                 }
6244                 ++p;
6245         }
6246         maxCols = max(cols, maxCols);
6247         Tabular * loctab;
6248         idx_type cell = 0;
6249         col_type ocol = 0;
6250         row_type row = 0;
6251         if (usePaste) {
6252                 paste_tabular.reset(new Tabular(buffer_, rows, maxCols));
6253                 loctab = paste_tabular.get();
6254                 cols = 0;
6255                 dirtyTabularStack(true);
6256         } else {
6257                 loctab = &tabular;
6258                 cell = bv.cursor().idx();
6259                 ocol = tabular.cellColumn(cell);
6260                 row = tabular.cellRow(cell);
6261         }
6262
6263         size_t op = 0;
6264         idx_type const cells = loctab->numberofcells;
6265         p = 0;
6266         cols = ocol;
6267         rows = loctab->nrows();
6268         col_type const columns = loctab->ncols();
6269
6270         while (cell < cells && p < len && row < rows &&
6271                (p = buf.find_first_of(from_ascii("\t\n"), p)) != docstring::npos)
6272         {
6273                 if (p >= len)
6274                         break;
6275                 switch (buf[p]) {
6276                 case '\t':
6277                         // we can only set this if we are not too far right
6278                         if (cols < columns) {
6279                                 shared_ptr<InsetTableCell> inset = loctab->cellInset(cell);
6280                                 Font const font = bv.textMetrics(&inset->text()).
6281                                         displayFont(0, 0);
6282                                 inset->setText(buf.substr(op, p - op), font,
6283                                                buffer().params().trackChanges);
6284                                 ++cols;
6285                                 ++cell;
6286                         }
6287                         break;
6288                 case '\n':
6289                         // we can only set this if we are not too far right
6290                         if (cols < columns) {
6291                                 shared_ptr<InsetTableCell> inset = tabular.cellInset(cell);
6292                                 Font const font = bv.textMetrics(&inset->text()).
6293                                         displayFont(0, 0);
6294                                 inset->setText(buf.substr(op, p - op), font,
6295                                                buffer().params().trackChanges);
6296                         }
6297                         cols = ocol;
6298                         ++row;
6299                         if (row < rows)
6300                                 cell = loctab->cellIndex(row, cols);
6301                         break;
6302                 }
6303                 ++p;
6304                 op = p;
6305         }
6306         // check for the last cell if there is no trailing '\n'
6307         if (cell < cells && op < len) {
6308                 shared_ptr<InsetTableCell> inset = loctab->cellInset(cell);
6309                 Font const font = bv.textMetrics(&inset->text()).displayFont(0, 0);
6310                 inset->setText(buf.substr(op, len - op), font,
6311                         buffer().params().trackChanges);
6312         }
6313         return true;
6314 }
6315
6316
6317 void InsetTabular::addPreview(DocIterator const & inset_pos,
6318         PreviewLoader & loader) const
6319 {
6320         DocIterator cell_pos = inset_pos;
6321
6322         cell_pos.push_back(CursorSlice(*const_cast<InsetTabular *>(this)));
6323         for (row_type r = 0; r < tabular.nrows(); ++r) {
6324                 for (col_type c = 0; c < tabular.ncols(); ++c) {
6325                         cell_pos.top().idx() = tabular.cellIndex(r, c);
6326                         tabular.cellInset(r, c)->addPreview(cell_pos, loader);
6327                 }
6328         }
6329 }
6330
6331
6332 bool InsetTabular::completionSupported(Cursor const & cur) const
6333 {
6334         Cursor const & bvCur = cur.bv().cursor();
6335         if (&bvCur.inset() != this)
6336                 return false;
6337         return cur.text()->completionSupported(cur);
6338 }
6339
6340
6341 bool InsetTabular::inlineCompletionSupported(Cursor const & cur) const
6342 {
6343         return completionSupported(cur);
6344 }
6345
6346
6347 bool InsetTabular::automaticInlineCompletion() const
6348 {
6349         return lyxrc.completion_inline_text;
6350 }
6351
6352
6353 bool InsetTabular::automaticPopupCompletion() const
6354 {
6355         return lyxrc.completion_popup_text;
6356 }
6357
6358
6359 bool InsetTabular::showCompletionCursor() const
6360 {
6361         return lyxrc.completion_cursor_text;
6362 }
6363
6364
6365 CompletionList const * InsetTabular::createCompletionList(Cursor const & cur) const
6366 {
6367         return completionSupported(cur) ? cur.text()->createCompletionList(cur) : 0;
6368 }
6369
6370
6371 docstring InsetTabular::completionPrefix(Cursor const & cur) const
6372 {
6373         if (!completionSupported(cur))
6374                 return docstring();
6375         return cur.text()->completionPrefix(cur);
6376 }
6377
6378
6379 bool InsetTabular::insertCompletion(Cursor & cur, docstring const & s, bool finished)
6380 {
6381         if (!completionSupported(cur))
6382                 return false;
6383
6384         return cur.text()->insertCompletion(cur, s, finished);
6385 }
6386
6387
6388 void InsetTabular::completionPosAndDim(Cursor const & cur, int & x, int & y, 
6389                                     Dimension & dim) const
6390 {
6391         TextMetrics const & tm = cur.bv().textMetrics(cur.text());
6392         tm.completionPosAndDim(cur, x, y, dim);
6393 }
6394
6395
6396 void InsetTabular::string2params(string const & in, InsetTabular & inset)
6397 {
6398         istringstream data(in);
6399         Lexer lex;
6400         lex.setStream(data);
6401
6402         if (in.empty())
6403                 return;
6404
6405         string token;
6406         lex >> token;
6407         if (!lex || token != "tabular") {
6408                 LYXERR0("Expected arg 1 to be \"tabular\" in " << in);
6409                 return;
6410         }
6411
6412         // This is part of the inset proper that is usually swallowed
6413         // by Buffer::readInset
6414         lex >> token;
6415         if (!lex || token != "Tabular") {
6416                 LYXERR0("Expected arg 2 to be \"Tabular\" in " << in);
6417                 return;
6418         }
6419
6420         inset.read(lex);
6421 }
6422
6423
6424 string InsetTabular::params2string(InsetTabular const & inset)
6425 {
6426         ostringstream data;
6427         data << "tabular" << ' ';
6428         inset.write(data);
6429         data << "\\end_inset\n";
6430         return data.str();
6431 }
6432
6433
6434 } // namespace lyx