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