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