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