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