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