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