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