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