]> git.lyx.org Git - lyx.git/blob - src/insets/InsetTabular.cpp
Merge branch 'master' into biblatex2
[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 = (bool)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         TexRow::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                                 bool decimal = false;
2766                                 switch (column_info[c].alignment) {
2767                                 case LYX_ALIGN_LEFT:
2768                                         os << ">{\\raggedright}";
2769                                         break;
2770                                 case LYX_ALIGN_RIGHT:
2771                                         os << ">{\\raggedleft}";
2772                                         break;
2773                                 case LYX_ALIGN_CENTER:
2774                                         os << ">{\\centering}";
2775                                         break;
2776                                 case LYX_ALIGN_NONE:
2777                                 case LYX_ALIGN_BLOCK:
2778                                 case LYX_ALIGN_LAYOUT:
2779                                 case LYX_ALIGN_SPECIAL:
2780                                         break;
2781                                 case LYX_ALIGN_DECIMAL:
2782                                         os << ">{\\raggedleft}";
2783                                         decimal = true;
2784                                         break;
2785                                 }
2786
2787                                 char valign = 'p';
2788                                 switch (column_info[c].valignment) {
2789                                 case LYX_VALIGN_TOP:
2790                                         // this is the default
2791                                         break;
2792                                 case LYX_VALIGN_MIDDLE:
2793                                         valign = 'm';
2794                                         break;
2795                                 case LYX_VALIGN_BOTTOM:
2796                                         valign = 'b';
2797                                         break;
2798                                 }
2799                                 os << valign;
2800
2801                                 // Fixed-width cells with alignment at decimal separator
2802                                 // are output as two cells of half the width with the decimal
2803                                 // separator as column sep. This effectively puts the content
2804                                 // centered, which differs from the normal decimal sep alignment
2805                                 // and is not ideal, but we cannot do better ATM (see #9568).
2806                                 // FIXME: Implement proper decimal sep alignment, e.g. via siunitx.
2807                                 if (decimal) {
2808                                         docstring const halffixedwith =
2809                                                 from_ascii(Length(column_info[c].p_width.value() / 2,
2810                                                                   column_info[c].p_width.unit()).asLatexString());
2811                                         os << '{'
2812                                            << halffixedwith
2813                                            << '}'
2814                                            << "@{\\extracolsep{0pt}" << column_info[c].decimal_point << "}"
2815                                            << valign
2816                                            << '{'
2817                                            << halffixedwith
2818                                            << '}';
2819                                 } else
2820                                         os << '{'
2821                                            << from_ascii(column_info[c].p_width.asLatexString())
2822                                            << '}';
2823                         } else {
2824                                 switch (column_info[c].alignment) {
2825                                 case LYX_ALIGN_LEFT:
2826                                         os << 'l';
2827                                         break;
2828                                 case LYX_ALIGN_RIGHT:
2829                                         os << 'r';
2830                                         break;
2831                                 case LYX_ALIGN_DECIMAL:
2832                                         os << "r@{\\extracolsep{0pt}" << column_info[c].decimal_point << "}l";
2833                                         break;
2834                                 default:
2835                                         os << 'c';
2836                                         break;
2837                                 }
2838                         } // end if else !column_info[i].p_width
2839                 } // end if else !column_info[i].align_special
2840                 if (columnRightLine(c))
2841                         os << '|';
2842         }
2843         os << "}\n";
2844
2845         TeXLongtableHeaderFooter(os, runparams);
2846
2847         //+---------------------------------------------------------------------
2848         //+                      the single row and columns (cells)            +
2849         //+---------------------------------------------------------------------
2850
2851         for (row_type r = 0; r < nrows(); ++r) {
2852                 if (isValidRow(r)) {
2853                         TeXRow(os, r, runparams);
2854                         if (is_long_tabular && row_info[r].newpage)
2855                                 os << "\\newpage\n";
2856                 }
2857         }
2858
2859         //+---------------------------------------------------------------------
2860         //+                      the closing of the tabular                    +
2861         //+---------------------------------------------------------------------
2862
2863         if (is_long_tabular)
2864                 os << "\\end{longtable}";
2865         else {
2866                 if (is_tabular_star)
2867                         os << "\\end{tabular*}";
2868                 else
2869                         os << "\\end{tabular}";
2870         }
2871
2872         if (rotate != 0)
2873                 os << breakln << "\\end{turn}";
2874
2875         if (!TexRow::isNone(pos))
2876                 os.texrow().start(pos);
2877 }
2878
2879
2880 int Tabular::docbookRow(odocstream & os, row_type row,
2881                            OutputParams const & runparams) const
2882 {
2883         int ret = 0;
2884         idx_type cell = getFirstCellInRow(row);
2885
2886         os << "<row>\n";
2887         for (col_type c = 0; c < ncols(); ++c) {
2888                 if (isPartOfMultiColumn(row, c))
2889                         continue;
2890
2891                 os << "<entry align=\"";
2892                 switch (getAlignment(cell)) {
2893                 case LYX_ALIGN_LEFT:
2894                         os << "left";
2895                         break;
2896                 case LYX_ALIGN_RIGHT:
2897                         os << "right";
2898                         break;
2899                 default:
2900                         os << "center";
2901                         break;
2902                 }
2903
2904                 os << "\" valign=\"";
2905                 switch (getVAlignment(cell)) {
2906                 case LYX_VALIGN_TOP:
2907                         os << "top";
2908                         break;
2909                 case LYX_VALIGN_BOTTOM:
2910                         os << "bottom";
2911                         break;
2912                 case LYX_VALIGN_MIDDLE:
2913                         os << "middle";
2914                 }
2915                 os << '"';
2916
2917                 if (isMultiColumn(cell)) {
2918                         os << " namest=\"col" << c << "\" ";
2919                         os << "nameend=\"col" << c + columnSpan(cell) - 1 << '"';
2920                 }
2921
2922                 os << '>';
2923                 ret += cellInset(cell)->docbook(os, runparams);
2924                 os << "</entry>\n";
2925                 ++cell;
2926         }
2927         os << "</row>\n";
2928         return ret;
2929 }
2930
2931
2932 int Tabular::docbook(odocstream & os, OutputParams const & runparams) const
2933 {
2934         int ret = 0;
2935
2936         //+---------------------------------------------------------------------
2937         //+                      first the opening preamble                    +
2938         //+---------------------------------------------------------------------
2939
2940         os << "<tgroup cols=\"" << ncols()
2941            << "\" colsep=\"1\" rowsep=\"1\">\n";
2942
2943         for (col_type c = 0; c < ncols(); ++c) {
2944                 os << "<colspec colname=\"col" << c << "\" align=\"";
2945                 switch (column_info[c].alignment) {
2946                 case LYX_ALIGN_LEFT:
2947                         os << "left";
2948                         break;
2949                 case LYX_ALIGN_RIGHT:
2950                         os << "right";
2951                         break;
2952                 default:
2953                         os << "center";
2954                         break;
2955                 }
2956                 os << '"';
2957                 if (runparams.flavor == OutputParams::XML)
2958                         os << '/';
2959                 os << ">\n";
2960                 ++ret;
2961         }
2962
2963         //+---------------------------------------------------------------------
2964         //+                      Long Tabular case                             +
2965         //+---------------------------------------------------------------------
2966
2967         // output caption info
2968         // The caption flag wins over head/foot
2969         if (haveLTCaption()) {
2970                 os << "<caption>\n";
2971                 ++ret;
2972                 for (row_type r = 0; r < nrows(); ++r) {
2973                         if (row_info[r].caption) {
2974                                 ret += docbookRow(os, r, runparams);
2975                         }
2976                 }
2977                 os << "</caption>\n";
2978                 ++ret;
2979         }
2980         // output header info
2981         if (haveLTHead(false) || haveLTFirstHead(false)) {
2982                 os << "<thead>\n";
2983                 ++ret;
2984                 for (row_type r = 0; r < nrows(); ++r) {
2985                         if ((row_info[r].endhead || row_info[r].endfirsthead) &&
2986                             !row_info[r].caption) {
2987                                 ret += docbookRow(os, r, runparams);
2988                         }
2989                 }
2990                 os << "</thead>\n";
2991                 ++ret;
2992         }
2993         // output footer info
2994         if (haveLTFoot(false) || haveLTLastFoot(false)) {
2995                 os << "<tfoot>\n";
2996                 ++ret;
2997                 for (row_type r = 0; r < nrows(); ++r) {
2998                         if ((row_info[r].endfoot || row_info[r].endlastfoot) &&
2999                             !row_info[r].caption) {
3000                                 ret += docbookRow(os, r, runparams);
3001                         }
3002                 }
3003                 os << "</tfoot>\n";
3004                 ++ret;
3005         }
3006
3007         //+---------------------------------------------------------------------
3008         //+                      the single row and columns (cells)            +
3009         //+---------------------------------------------------------------------
3010
3011         os << "<tbody>\n";
3012         ++ret;
3013         for (row_type r = 0; r < nrows(); ++r) {
3014                 if (isValidRow(r)) {
3015                         ret += docbookRow(os, r, runparams);
3016                 }
3017         }
3018         os << "</tbody>\n";
3019         ++ret;
3020         //+---------------------------------------------------------------------
3021         //+                      the closing of the tabular                    +
3022         //+---------------------------------------------------------------------
3023
3024         os << "</tgroup>";
3025         ++ret;
3026
3027         return ret;
3028 }
3029
3030
3031 docstring Tabular::xhtmlRow(XHTMLStream & xs, row_type row,
3032                            OutputParams const & runparams, bool header) const
3033 {
3034         docstring ret;
3035         string const celltag = header ? "th" : "td";
3036         idx_type cell = getFirstCellInRow(row);
3037
3038         xs << html::StartTag("tr");
3039         for (col_type c = 0; c < ncols(); ++c) {
3040                 if (isPartOfMultiColumn(row, c) || isPartOfMultiRow(row, c))
3041                         continue;
3042
3043                 stringstream attr;
3044                 
3045                 Length const cwidth = column_info[c].p_width;
3046                 if (!cwidth.zero()) {
3047                         string const hwidth = cwidth.asHTMLString();
3048                         attr << "style =\"width: " << hwidth << ";\" ";
3049                 }
3050                 
3051                 attr << "align='";
3052                 switch (getAlignment(cell)) {
3053                 case LYX_ALIGN_LEFT:
3054                         attr << "left";
3055                         break;
3056                 case LYX_ALIGN_RIGHT:
3057                         attr << "right";
3058                         break;
3059                 default:
3060                         attr << "center";
3061                         break;
3062                 }
3063                 attr << "'";
3064                 attr << " valign='";
3065                 switch (getVAlignment(cell)) {
3066                 case LYX_VALIGN_TOP:
3067                         attr << "top";
3068                         break;
3069                 case LYX_VALIGN_BOTTOM:
3070                         attr << "bottom";
3071                         break;
3072                 case LYX_VALIGN_MIDDLE:
3073                         attr << "middle";
3074                 }
3075                 attr << "'";
3076
3077                 if (isMultiColumn(cell))
3078                         attr << " colspan='" << columnSpan(cell) << "'";
3079                 else if (isMultiRow(cell))
3080                         attr << " rowspan='" << rowSpan(cell) << "'";
3081
3082                 xs << html::StartTag(celltag, attr.str(), true) << html::CR();
3083                 ret += cellInset(cell)->xhtml(xs, runparams);
3084                 xs << html::EndTag(celltag) << html::CR();
3085                 ++cell;
3086         }
3087         xs << html::EndTag("tr");
3088         return ret;
3089 }
3090
3091
3092 docstring Tabular::xhtml(XHTMLStream & xs, OutputParams const & runparams) const
3093 {
3094         docstring ret;
3095
3096         if (is_long_tabular) {
3097                 // we'll wrap it in a div, so as to deal with alignment
3098                 string align;
3099                 switch (longtabular_alignment) {
3100                 case LYX_LONGTABULAR_ALIGN_LEFT:
3101                         align = "left";
3102                         break;
3103                 case LYX_LONGTABULAR_ALIGN_CENTER:
3104                         align = "center";
3105                         break;
3106                 case LYX_LONGTABULAR_ALIGN_RIGHT:
3107                         align = "right";
3108                         break;
3109                 }
3110                 xs << html::StartTag("div", "class='longtable' style='text-align: " + align + ";'")
3111                    << html::CR();
3112                 // The caption flag wins over head/foot
3113                 if (haveLTCaption()) {
3114                         xs << html::StartTag("div", "class='longtable-caption' style='text-align: " + align + ";'")
3115                            << html::CR();
3116                         for (row_type r = 0; r < nrows(); ++r)
3117                                 if (row_info[r].caption)
3118                                         ret += xhtmlRow(xs, r, runparams);
3119                         xs << html::EndTag("div") << html::CR();
3120                 }
3121         }
3122
3123         xs << html::StartTag("table") << html::CR();
3124
3125         // output header info
3126         bool const havefirsthead = haveLTFirstHead(false);
3127         // if we have a first head, then we are going to ignore the
3128         // headers for the additional pages, since there aren't any
3129         // in XHTML. this test accomplishes that.
3130         bool const havehead = !havefirsthead && haveLTHead(false);
3131         if (havehead || havefirsthead) {
3132                 xs << html::StartTag("thead") << html::CR();
3133                 for (row_type r = 0; r < nrows(); ++r) {
3134                         if (((havefirsthead && row_info[r].endfirsthead) ||
3135                              (havehead && row_info[r].endhead)) &&
3136                             !row_info[r].caption) {
3137                                 ret += xhtmlRow(xs, r, runparams, true);
3138                         }
3139                 }
3140                 xs << html::EndTag("thead") << html::CR();
3141         }
3142         // output footer info
3143         bool const havelastfoot = haveLTLastFoot(false);
3144         // as before.
3145         bool const havefoot = !havelastfoot && haveLTFoot(false);
3146         if (havefoot || havelastfoot) {
3147                 xs << html::StartTag("tfoot") << html::CR();
3148                 for (row_type r = 0; r < nrows(); ++r) {
3149                         if (((havelastfoot && row_info[r].endlastfoot) ||
3150                              (havefoot && row_info[r].endfoot)) &&
3151                             !row_info[r].caption) {
3152                                 ret += xhtmlRow(xs, r, runparams);
3153                         }
3154                 }
3155                 xs << html::EndTag("tfoot") << html::CR();
3156         }
3157
3158         xs << html::StartTag("tbody") << html::CR();
3159         for (row_type r = 0; r < nrows(); ++r) {
3160                 if (isValidRow(r)) {
3161                         ret += xhtmlRow(xs, r, runparams);
3162                 }
3163         }
3164         xs << html::EndTag("tbody")
3165            << html::CR()
3166            << html::EndTag("table")
3167            << html::CR();
3168         if (is_long_tabular)
3169                 xs << html::EndTag("div") << html::CR();
3170         return ret;
3171 }
3172
3173
3174 bool Tabular::plaintextTopHLine(odocstringstream & os, row_type row,
3175                                    vector<unsigned int> const & clen) const
3176 {
3177         idx_type const fcell = getFirstCellInRow(row);
3178         idx_type const n = numberOfCellsInRow(row) + fcell;
3179         idx_type tmp = 0;
3180
3181         for (idx_type i = fcell; i < n; ++i) {
3182                 if (topLine(i)) {
3183                         ++tmp;
3184                         break;
3185                 }
3186         }
3187         if (!tmp)
3188                 return false;
3189
3190         char_type ch;
3191         for (idx_type i = fcell; i < n; ++i) {
3192                 if (topLine(i)) {
3193                         if (leftLine(i))
3194                                 os << "+-";
3195                         else
3196                                 os << "--";
3197                         ch = '-';
3198                 } else {
3199                         os << "  ";
3200                         ch = ' ';
3201                 }
3202                 col_type column = cellColumn(i);
3203                 int len = clen[column];
3204                 while (column < ncols() - 1
3205                        && isPartOfMultiColumn(row, ++column))
3206                         len += clen[column] + 4;
3207                 os << docstring(len, ch);
3208                 if (topLine(i)) {
3209                         if (rightLine(i))
3210                                 os << "-+";
3211                         else
3212                                 os << "--";
3213                 } else {
3214                         os << "  ";
3215                 }
3216         }
3217         os << endl;
3218         return true;
3219 }
3220
3221
3222 bool Tabular::plaintextBottomHLine(odocstringstream & os, row_type row,
3223                                       vector<unsigned int> const & clen) const
3224 {
3225         idx_type const fcell = getFirstCellInRow(row);
3226         idx_type const n = numberOfCellsInRow(row) + fcell;
3227         idx_type tmp = 0;
3228
3229         for (idx_type i = fcell; i < n; ++i) {
3230                 if (bottomLine(i)) {
3231                         ++tmp;
3232                         break;
3233                 }
3234         }
3235         if (!tmp)
3236                 return false;
3237
3238         char_type ch;
3239         for (idx_type i = fcell; i < n; ++i) {
3240                 if (bottomLine(i)) {
3241                         if (leftLine(i))
3242                                 os << "+-";
3243                         else
3244                                 os << "--";
3245                         ch = '-';
3246                 } else {
3247                         os << "  ";
3248                         ch = ' ';
3249                 }
3250                 col_type column = cellColumn(i);
3251                 int len = clen[column];
3252                 while (column < ncols() - 1 && isPartOfMultiColumn(row, ++column))
3253                         len += clen[column] + 4;
3254                 os << docstring(len, ch);
3255                 if (bottomLine(i)) {
3256                         if (rightLine(i))
3257                                 os << "-+";
3258                         else
3259                                 os << "--";
3260                 } else {
3261                         os << "  ";
3262                 }
3263         }
3264         os << endl;
3265         return true;
3266 }
3267
3268
3269 void Tabular::plaintextPrintCell(odocstringstream & os,
3270                                OutputParams const & runparams,
3271                                idx_type cell, row_type row, col_type column,
3272                                vector<unsigned int> const & clen,
3273                                bool onlydata, size_t max_length) const
3274 {
3275         odocstringstream sstr;
3276         cellInset(cell)->plaintext(sstr, runparams, max_length);
3277
3278         if (onlydata) {
3279                 os << sstr.str();
3280                 return;
3281         }
3282
3283         if (leftLine(cell))
3284                 os << "| ";
3285         else
3286                 os << "  ";
3287
3288         unsigned int len1 = sstr.str().length();
3289         unsigned int len2 = clen[column];
3290         while (column < ncols() - 1 && isPartOfMultiColumn(row, ++column))
3291                 len2 += clen[column] + 4;
3292         len2 -= len1;
3293
3294         switch (getAlignment(cell)) {
3295         default:
3296         case LYX_ALIGN_LEFT:
3297                 len1 = 0;
3298                 break;
3299         case LYX_ALIGN_RIGHT:
3300                 len1 = len2;
3301                 len2 = 0;
3302                 break;
3303         case LYX_ALIGN_CENTER:
3304                 len1 = len2 / 2;
3305                 len2 -= len1;
3306                 break;
3307         }
3308
3309         os << docstring(len1, ' ') << sstr.str()
3310            << docstring(len2, ' ');
3311
3312         if (rightLine(cell))
3313                 os << " |";
3314         else
3315                 os << "  ";
3316 }
3317
3318
3319 void Tabular::plaintext(odocstringstream & os,
3320                            OutputParams const & runparams, int const depth,
3321                            bool onlydata, char_type delim, size_t max_length) const
3322 {
3323         // first calculate the width of the single columns
3324         vector<unsigned int> clen(ncols());
3325
3326         if (!onlydata) {
3327                 // first all non multicolumn cells!
3328                 for (col_type c = 0; c < ncols(); ++c) {
3329                         clen[c] = 0;
3330                         for (row_type r = 0; r < nrows(); ++r) {
3331                                 idx_type cell = cellIndex(r, c);
3332                                 if (isMultiColumn(cell))
3333                                         continue;
3334                                 odocstringstream sstr;
3335                                 cellInset(cell)->plaintext(sstr, runparams, max_length);
3336                                 if (clen[c] < sstr.str().length())
3337                                         clen[c] = sstr.str().length();
3338                         }
3339                 }
3340                 // then all multicolumn cells!
3341                 for (col_type c = 0; c < ncols(); ++c) {
3342                         for (row_type r = 0; r < nrows(); ++r) {
3343                                 idx_type cell = cellIndex(r, c);
3344                                 if (cell_info[r][c].multicolumn != CELL_BEGIN_OF_MULTICOLUMN)
3345                                         continue;
3346                                 odocstringstream sstr;
3347                                 cellInset(cell)->plaintext(sstr, runparams, max_length);
3348                                 int len = int(sstr.str().length());
3349                                 idx_type const n = columnSpan(cell);
3350                                 for (col_type k = c; len > 0 && k < c + n - 1; ++k)
3351                                         len -= clen[k];
3352                                 if (len > int(clen[c + n - 1]))
3353                                         clen[c + n - 1] = len;
3354                         }
3355                 }
3356         }
3357         idx_type cell = 0;
3358         for (row_type r = 0; r < nrows(); ++r) {
3359                 if (!onlydata && plaintextTopHLine(os, r, clen))
3360                         os << docstring(depth * 2, ' ');
3361                 for (col_type c = 0; c < ncols(); ++c) {
3362                         if (isPartOfMultiColumn(r, c) || isPartOfMultiRow(r,c))
3363                                 continue;
3364                         if (onlydata && c > 0)
3365                                 // we don't use operator<< for single UCS4 character.
3366                                 // see explanation in docstream.h
3367                                 os.put(delim);
3368                         plaintextPrintCell(os, runparams, cell, r, c, clen, onlydata, max_length);
3369                         ++cell;
3370                         if (os.str().size() > max_length)
3371                                 break;
3372                 }
3373                 os << endl;
3374                 if (!onlydata) {
3375                         os << docstring(depth * 2, ' ');
3376                         if (plaintextBottomHLine(os, r, clen))
3377                                 os << docstring(depth * 2, ' ');
3378                 }
3379                 if (os.str().size() > max_length)
3380                         break;
3381         }
3382 }
3383
3384
3385 shared_ptr<InsetTableCell> Tabular::cellInset(idx_type cell)
3386 {
3387         return cell_info[cellRow(cell)][cellColumn(cell)].inset;
3388 }
3389
3390
3391 shared_ptr<InsetTableCell> Tabular::cellInset(row_type row, col_type column)
3392 {
3393         return cell_info[row][column].inset;
3394 }
3395
3396
3397 InsetTableCell const * Tabular::cellInset(idx_type cell) const
3398 {
3399         return cell_info[cellRow(cell)][cellColumn(cell)].inset.get();
3400 }
3401
3402
3403 void Tabular::setCellInset(row_type row, col_type column,
3404                            shared_ptr<InsetTableCell> ins)
3405 {
3406         CellData & cd = cell_info[row][column];
3407         cd.inset = ins;
3408 }
3409
3410
3411 void Tabular::validate(LaTeXFeatures & features) const
3412 {
3413         features.require("NeedTabularnewline");
3414         if (use_booktabs)
3415                 features.require("booktabs");
3416         if (is_long_tabular)
3417                 features.require("longtable");
3418         if (needRotating())
3419                 features.require("rotating");
3420         for (idx_type cell = 0; cell < numberofcells; ++cell) {
3421                 if (isMultiRow(cell))
3422                         features.require("multirow");
3423                 if (getVAlignment(cell) != LYX_VALIGN_TOP
3424                     || !getPWidth(cell).zero())
3425                         features.require("array");
3426                 cellInset(cell)->validate(features);
3427         }
3428 }
3429
3430
3431 Tabular::BoxType Tabular::useParbox(idx_type cell) const
3432 {
3433         ParagraphList const & parlist = cellInset(cell)->paragraphs();
3434         ParagraphList::const_iterator cit = parlist.begin();
3435         ParagraphList::const_iterator end = parlist.end();
3436
3437         for (; cit != end; ++cit)
3438                 for (int i = 0; i < cit->size(); ++i)
3439                         if (cit->isNewline(i))
3440                                 return BOX_PARBOX;
3441
3442         return BOX_NONE;
3443 }
3444
3445
3446 /////////////////////////////////////////////////////////////////////
3447 //
3448 // InsetTableCell
3449 //
3450 /////////////////////////////////////////////////////////////////////
3451
3452 InsetTableCell::InsetTableCell(Buffer * buf)
3453         : InsetText(buf, InsetText::PlainLayout), isFixedWidth(false),
3454           contentAlign(LYX_ALIGN_CENTER)
3455 {}
3456
3457
3458 bool InsetTableCell::forcePlainLayout(idx_type) const
3459 {
3460         return !isFixedWidth;
3461 }
3462
3463
3464 bool InsetTableCell::allowParagraphCustomization(idx_type) const
3465 {
3466         return isFixedWidth;
3467 }
3468
3469
3470 bool InsetTableCell::forceLocalFontSwitch() const
3471 {
3472         return isFixedWidth;
3473 }
3474
3475
3476 bool InsetTableCell::getStatus(Cursor & cur, FuncRequest const & cmd,
3477         FuncStatus & status) const
3478 {
3479         bool enabled = true;
3480         switch (cmd.action()) {
3481         case LFUN_MATH_DISPLAY:
3482                 if (!hasFixedWidth()) {
3483                         enabled = false;
3484                         break;
3485                 } //fall-through
3486         default:
3487                 return InsetText::getStatus(cur, cmd, status);
3488         }
3489         status.setEnabled(enabled);
3490         return true;
3491 }
3492
3493 docstring InsetTableCell::asString(bool intoInsets)
3494 {
3495         docstring retval;
3496         if (paragraphs().empty())
3497                 return retval;
3498         ParagraphList::const_iterator it = paragraphs().begin();
3499         ParagraphList::const_iterator en = paragraphs().end();
3500         bool first = true;
3501         for (; it != en; ++it) {
3502                 if (!first)
3503                         retval += "\n";
3504                 else
3505                         first = false;
3506                 retval += it->asString(intoInsets ? AS_STR_INSETS : AS_STR_NONE);
3507         }
3508         return retval;
3509 }
3510
3511
3512 void InsetTableCell::addToToc(DocIterator const & di, bool output_active,
3513                                                           UpdateType utype) const
3514 {
3515         InsetText::iterateForToc(di, output_active, utype);
3516 }
3517
3518
3519 docstring InsetTableCell::xhtml(XHTMLStream & xs, OutputParams const & rp) const
3520 {
3521         if (!isFixedWidth)
3522                 return InsetText::insetAsXHTML(xs, rp, InsetText::JustText);
3523         return InsetText::xhtml(xs, rp);
3524 }
3525
3526
3527
3528 /////////////////////////////////////////////////////////////////////
3529 //
3530 // InsetTabular
3531 //
3532 /////////////////////////////////////////////////////////////////////
3533
3534 InsetTabular::InsetTabular(Buffer * buf, row_type rows,
3535                            col_type columns)
3536         : Inset(buf), tabular(buf, max(rows, row_type(1)), max(columns, col_type(1))),
3537           rowselect_(false), colselect_(false)
3538 {
3539 }
3540
3541
3542 InsetTabular::InsetTabular(InsetTabular const & tab)
3543         : Inset(tab), tabular(tab.tabular),
3544           rowselect_(false), colselect_(false)
3545 {
3546 }
3547
3548
3549 InsetTabular::~InsetTabular()
3550 {
3551         hideDialogs("tabular", this);
3552 }
3553
3554
3555 void InsetTabular::setBuffer(Buffer & buf)
3556 {
3557         tabular.setBuffer(buf);
3558         Inset::setBuffer(buf);
3559 }
3560
3561
3562 bool InsetTabular::insetAllowed(InsetCode code) const
3563 {
3564         switch (code) {
3565         case FLOAT_CODE:
3566         case MARGIN_CODE:
3567         case MATHMACRO_CODE:
3568         case WRAP_CODE:
3569                 return false;
3570
3571         case CAPTION_CODE:
3572                 return tabular.is_long_tabular;
3573
3574         default:
3575                 return true;
3576         }
3577 }
3578
3579
3580 bool InsetTabular::allowsCaptionVariation(std::string const & newtype) const
3581 {
3582         return tabular.is_long_tabular &&
3583                 (newtype == "Standard" || newtype == "Unnumbered");
3584 }
3585
3586
3587 void InsetTabular::write(ostream & os) const
3588 {
3589         os << "Tabular" << endl;
3590         tabular.write(os);
3591 }
3592
3593
3594 string InsetTabular::contextMenu(BufferView const &, int, int) const
3595 {
3596         // FIXME: depending on the selection state,
3597         // we could offer a different menu.
3598         return cell(0)->contextMenuName() + ";" + contextMenuName();
3599 }
3600
3601
3602 string InsetTabular::contextMenuName() const
3603 {
3604         return "context-tabular";
3605 }
3606
3607
3608 void InsetTabular::read(Lexer & lex)
3609 {
3610         //bool const old_format = (lex.getString() == "\\LyXTable");
3611
3612         tabular.read(lex);
3613
3614         //if (old_format)
3615         //      return;
3616
3617         lex.next();
3618         string token = lex.getString();
3619         while (lex && token != "\\end_inset") {
3620                 lex.next();
3621                 token = lex.getString();
3622         }
3623         if (!lex)
3624                 lex.printError("Missing \\end_inset at this point. ");
3625 }
3626
3627
3628 int InsetTabular::rowFromY(Cursor & cur, int y) const
3629 {
3630         // top y coordinate of tabular
3631         int h = yo(cur.bv()) - tabular.rowAscent(0) + tabular.offsetVAlignment();
3632         row_type r = 0;
3633         for (; r < tabular.nrows() && y > h; ++r)
3634                 h += tabular.rowAscent(r) + tabular.rowDescent(r)
3635                         + tabular.interRowSpace(r);
3636
3637         return r - 1;
3638 }
3639
3640
3641 int InsetTabular::columnFromX(Cursor & cur, int x) const
3642 {
3643         // left x coordinate of tabular
3644         int w = xo(cur.bv()) + ADD_TO_TABULAR_WIDTH;
3645         col_type c = 0;
3646         for (; c < tabular.ncols() && x > w; ++c)
3647                 w += tabular.cellWidth(c);
3648         return c - 1;
3649 }
3650
3651
3652 void InsetTabular::metrics(MetricsInfo & mi, Dimension & dim) const
3653 {
3654         //lyxerr << "InsetTabular::metrics: " << mi.base.bv << " width: " <<
3655         //      mi.base.textwidth << "\n";
3656         LBUFERR(mi.base.bv);
3657
3658         for (row_type r = 0; r < tabular.nrows(); ++r) {
3659                 int maxasc = 0;
3660                 int maxdes = 0;
3661                 for (col_type c = 0; c < tabular.ncols(); ++c) {
3662                         if (tabular.isPartOfMultiColumn(r, c)
3663                                 || tabular.isPartOfMultiRow(r, c))
3664                                 // multicolumn or multirow cell, but not first one
3665                                 continue;
3666                         idx_type const cell = tabular.cellIndex(r, c);
3667                         Dimension dim;
3668                         MetricsInfo m = mi;
3669                         Length const p_width = tabular.getPWidth(cell);
3670                         if (!p_width.zero())
3671                                 m.base.textwidth = p_width.inPixels(mi.base);
3672                         tabular.cellInset(cell)->metrics(m, dim);
3673                         if (!p_width.zero())
3674                                 dim.wid = m.base.textwidth;
3675                         tabular.cellInfo(cell).width = dim.wid + 2 * WIDTH_OF_LINE
3676                                 + tabular.interColumnSpace(cell);
3677
3678                         // FIXME(?): do we need a second metrics call?
3679                         TextMetrics const & tm =
3680                                 mi.base.bv->textMetrics(tabular.cellInset(cell)->getText(0));
3681
3682                         // determine horizontal offset because of decimal align (if necessary)
3683                         int decimal_width = 0;
3684                         if (tabular.getAlignment(cell) == LYX_ALIGN_DECIMAL) {
3685                                 InsetTableCell tail = InsetTableCell(*tabular.cellInset(cell));
3686                                 tail.setBuffer(tabular.buffer());
3687                                 // we need to set macrocontext position everywhere
3688                                 // otherwise we crash with nested insets (e.g. footnotes)
3689                                 // after decimal point
3690                                 DocIterator dit = tabular.cellInset(cell)->getText(0)->macrocontextPosition();
3691                                 dit.pop_back();
3692                                 dit.push_back(CursorSlice(tail));
3693                                 tail.setMacrocontextPositionRecursive(dit);
3694
3695                                 // remove text leading decimal point
3696                                 docstring const align_d = tabular.column_info[c].decimal_point;
3697                                 dit = separatorPos(&tail, align_d);
3698
3699                                 pit_type const psize = tail.paragraphs().front().size();
3700                                 if (dit) {
3701                                         tail.paragraphs().front().eraseChars(0,
3702                                                 dit.pos() < psize ? dit.pos() + 1 : psize, false);
3703                                         Dimension dim1;
3704                                         tail.metrics(m, dim1);
3705                                         decimal_width = dim1.width();
3706                                 }
3707                         }
3708                         tabular.cell_info[r][c].decimal_hoffset = tm.width() - decimal_width;
3709                         tabular.cell_info[r][c].decimal_width = decimal_width;
3710
3711                         // with LYX_VALIGN_BOTTOM the descent is relative to the last par
3712                         // = descent of text in last par + TEXT_TO_INSET_OFFSET:
3713                         int const lastpardes = tm.last().second->descent()
3714                                 + TEXT_TO_INSET_OFFSET;
3715                         int offset = 0;
3716                         switch (tabular.getVAlignment(cell)) {
3717                                 case Tabular::LYX_VALIGN_TOP:
3718                                         break;
3719                                 case Tabular::LYX_VALIGN_MIDDLE:
3720                                         offset = -(dim.des - lastpardes)/2;
3721                                         break;
3722                                 case Tabular::LYX_VALIGN_BOTTOM:
3723                                         offset = -(dim.des - lastpardes);
3724                                         break;
3725                         }
3726                         tabular.cell_info[r][c].voffset = offset;
3727                         maxasc = max(maxasc, dim.asc - offset);
3728                         maxdes = max(maxdes, dim.des + offset);
3729                 }
3730                 int const top_space = tabular.row_info[r].top_space_default ?
3731                         default_line_space :
3732                         tabular.row_info[r].top_space.inPixels(mi.base);
3733                 tabular.setRowAscent(r, maxasc + ADD_TO_HEIGHT + top_space);
3734                 int const bottom_space = tabular.row_info[r].bottom_space_default ?
3735                         default_line_space :
3736                         tabular.row_info[r].bottom_space.inPixels(mi.base);
3737                 tabular.setRowDescent(r, maxdes + ADD_TO_HEIGHT + bottom_space);
3738         }
3739
3740         tabular.updateColumnWidths();
3741         dim.asc = tabular.rowAscent(0) - tabular.offsetVAlignment();
3742         dim.des = tabular.height() - dim.asc;
3743         dim.wid = tabular.width() + 2 * ADD_TO_TABULAR_WIDTH;
3744 }
3745
3746
3747 bool InsetTabular::isCellSelected(Cursor & cur, row_type row, col_type col)
3748         const
3749 {
3750         if (&cur.inset() == this && cur.selection()) {
3751                 if (cur.selIsMultiCell()) {
3752                         row_type rs, re;
3753                         col_type cs, ce;
3754                         getSelection(cur, rs, re, cs, ce);
3755
3756                         idx_type const cell = tabular.cellIndex(row, col);
3757                         col_type const cspan = tabular.columnSpan(cell);
3758                         row_type const rspan = tabular.rowSpan(cell);
3759                         if (col + cspan - 1 >= cs && col <= ce
3760                                 && row + rspan - 1 >= rs && row <= re)
3761                                 return true;
3762                 } else
3763                         if (col == tabular.cellColumn(cur.idx())
3764                                 && row == tabular.cellRow(cur.idx())) {
3765                         CursorSlice const & beg = cur.selBegin();
3766                         CursorSlice const & end = cur.selEnd();
3767
3768                         if ((end.lastpos() > 0 || end.lastpit() > 0)
3769                                   && end.pos() == end.lastpos() && beg.pos() == 0
3770                                   && end.pit() == end.lastpit() && beg.pit() == 0)
3771                                 return true;
3772                 }
3773         }
3774         return false;
3775 }
3776
3777
3778 void InsetTabular::draw(PainterInfo & pi, int x, int y) const
3779 {
3780         x += ADD_TO_TABULAR_WIDTH;
3781
3782         BufferView * bv = pi.base.bv;
3783         Cursor & cur = pi.base.bv->cursor();
3784
3785         // FIXME: As the full background is painted in drawBackground(),
3786         // we have no choice but to do a full repaint for the Text cells.
3787         pi.full_repaint = true;
3788
3789         bool const original_selection_state = pi.selected;
3790
3791         idx_type idx = 0;
3792
3793         int yy = y + tabular.offsetVAlignment();
3794         for (row_type r = 0; r < tabular.nrows(); ++r) {
3795                 int nx = x;
3796                 for (col_type c = 0; c < tabular.ncols(); ++c) {
3797                         if (tabular.isPartOfMultiColumn(r, c))
3798                                 continue;
3799
3800                         idx = tabular.cellIndex(r, c);
3801
3802                         if (tabular.isPartOfMultiRow(r, c)) {
3803                                 nx += tabular.cellWidth(idx);
3804                                 continue;
3805                         }
3806
3807                         pi.selected |= isCellSelected(cur, r, c);
3808                         int const cx = nx + tabular.textHOffset(idx);
3809                         int const cy = yy + tabular.textVOffset(idx);
3810                         // Cache the Inset position.
3811                         bv->coordCache().insets().add(cell(idx).get(), cx, cy);
3812                         cell(idx)->draw(pi, cx, cy);
3813                         drawCellLines(pi, nx, yy, r, idx);
3814                         nx += tabular.cellWidth(idx);
3815                         pi.selected = original_selection_state;
3816                 }
3817
3818                 if (r + 1 < tabular.nrows())
3819                         yy += tabular.rowDescent(r) + tabular.rowAscent(r + 1)
3820                                 + tabular.interRowSpace(r + 1);
3821         }
3822 }
3823
3824
3825 void InsetTabular::drawBackground(PainterInfo & pi, int x, int y) const
3826 {
3827         x += ADD_TO_TABULAR_WIDTH;
3828         y += tabular.offsetVAlignment() - tabular.rowAscent(0);
3829         pi.pain.fillRectangle(x, y, tabular.width(), tabular.height(),
3830                 pi.backgroundColor(this));
3831 }
3832
3833
3834 void InsetTabular::drawSelection(PainterInfo & pi, int x, int y) const
3835 {
3836         Cursor & cur = pi.base.bv->cursor();
3837
3838         x += ADD_TO_TABULAR_WIDTH;
3839
3840         if (!cur.selection())
3841                 return;
3842         if (&cur.inset() != this)
3843                 return;
3844
3845         //resetPos(cur);
3846
3847         bool const full_cell_selected = isCellSelected(cur,
3848                 tabular.cellRow(cur.idx()), tabular.cellColumn(cur.idx()));
3849
3850         if (cur.selIsMultiCell() || full_cell_selected) {
3851                 for (row_type r = 0; r < tabular.nrows(); ++r) {
3852                         int xx = x;
3853                         for (col_type c = 0; c < tabular.ncols(); ++c) {
3854                                 if (tabular.isPartOfMultiColumn(r, c))
3855                                         continue;
3856
3857                                 idx_type const cell = tabular.cellIndex(r, c);
3858
3859                                 if (tabular.isPartOfMultiRow(r, c)) {
3860                                         xx += tabular.cellWidth(cell);
3861                                         continue;
3862                                 }
3863                                 int const w = tabular.cellWidth(cell);
3864                                 int const h = tabular.cellHeight(cell);
3865                                 int const yy = y - tabular.rowAscent(r) + tabular.offsetVAlignment();
3866                                 if (isCellSelected(cur, r, c))
3867                                         pi.pain.fillRectangle(xx, yy, w, h, Color_selection);
3868                                 xx += w;
3869                         }
3870                         if (r + 1 < tabular.nrows())
3871                                 y += tabular.rowDescent(r) + tabular.rowAscent(r + 1)
3872                                      + tabular.interRowSpace(r + 1);
3873                 }
3874
3875         }
3876         // FIXME: This code has no effect because InsetTableCell does not handle
3877         // drawSelection other than the trivial implementation in Inset.
3878         //else {
3879         //      x += cellXPos(cur.idx());
3880         //      x += tabular.textHOffset(cur.idx());
3881         //      cell(cur.idx())->drawSelection(pi, x, 0 /* ignored */);
3882         //}
3883 }
3884
3885
3886 void InsetTabular::drawCellLines(PainterInfo & pi, int x, int y,
3887                                  row_type row, idx_type cell) const
3888 {
3889         y -= tabular.rowAscent(row);
3890         int const w = tabular.cellWidth(cell);
3891         int const h = tabular.cellHeight(cell);
3892         Color const linecolor = pi.textColor(Color_tabularline);
3893         Color const gridcolor = pi.textColor(Color_tabularonoffline);
3894
3895         // Top
3896         bool drawline = tabular.topLine(cell)
3897                 || (row > 0 && tabular.bottomLine(tabular.cellAbove(cell)));
3898         pi.pain.line(x, y, x + w, y,
3899                 drawline ? linecolor : gridcolor,
3900                 drawline ? Painter::line_solid : Painter::line_onoffdash);
3901
3902         // Bottom
3903         drawline = tabular.bottomLine(cell);
3904         pi.pain.line(x, y + h, x + w, y + h,
3905                 drawline ? linecolor : gridcolor,
3906                 drawline ? Painter::line_solid : Painter::line_onoffdash);
3907
3908         // Left
3909         col_type const col = tabular.cellColumn(cell);
3910         drawline = tabular.leftLine(cell)
3911                 || (col > 0 && tabular.rightLine(tabular.cellIndex(row, col - 1)));
3912         pi.pain.line(x, y, x, y + h,
3913                 drawline ? linecolor : gridcolor,
3914                 drawline ? Painter::line_solid : Painter::line_onoffdash);
3915
3916         // Right
3917         x -= tabular.interColumnSpace(cell);
3918         col_type next_cell_col = col + 1;
3919         while (next_cell_col < tabular.ncols()
3920                 && tabular.isMultiColumn(tabular.cellIndex(row, next_cell_col)))
3921                 next_cell_col++;
3922         drawline = tabular.rightLine(cell)
3923                    || (next_cell_col < tabular.ncols()
3924                        && tabular.leftLine(tabular.cellIndex(row, next_cell_col)));
3925         pi.pain.line(x + w, y, x + w, y + h,
3926                 drawline ? linecolor : gridcolor,
3927                 drawline ? Painter::line_solid : Painter::line_onoffdash);
3928 }
3929
3930
3931 void InsetTabular::edit(Cursor & cur, bool front, EntryDirection)
3932 {
3933         //lyxerr << "InsetTabular::edit: " << this << endl;
3934         cur.finishUndo();
3935         cur.push(*this);
3936         if (front) {
3937                 if (isRightToLeft(cur))
3938                         cur.idx() = tabular.getLastCellInRow(0);
3939                 else
3940                         cur.idx() = 0;
3941                 cur.pit() = 0;
3942                 cur.pos() = 0;
3943         } else {
3944                 if (isRightToLeft(cur))
3945                         cur.idx() = tabular.getFirstCellInRow(tabular.nrows() - 1);
3946                 else
3947                         cur.idx() = tabular.numberofcells - 1;
3948                 cur.pit() = 0;
3949                 cur.pos() = cur.lastpos(); // FIXME crude guess
3950         }
3951         cur.setCurrentFont();
3952         // FIXME: this accesses the position cache before it is initialized
3953         //cur.bv().fitCursor();
3954 }
3955
3956
3957 void InsetTabular::updateBuffer(ParIterator const & it, UpdateType utype)
3958 {
3959         // In a longtable, tell captions what the current float is
3960         Counters & cnts = buffer().masterBuffer()->params().documentClass().counters();
3961         string const saveflt = cnts.current_float();
3962         if (tabular.is_long_tabular) {
3963                 cnts.current_float("table");
3964                 // in longtables, we only step the counter once
3965                 cnts.step(from_ascii("table"), utype);
3966                 cnts.isLongtable(true);
3967         }
3968
3969         ParIterator it2 = it;
3970         it2.forwardPos();
3971         size_t const end = it2.nargs();
3972         for ( ; it2.idx() < end; it2.top().forwardIdx())
3973                 buffer().updateBuffer(it2, utype);
3974
3975         //reset afterwards
3976         if (tabular.is_long_tabular) {
3977                 cnts.current_float(saveflt);
3978                 cnts.isLongtable(false);
3979         }
3980 }
3981
3982
3983 void InsetTabular::addToToc(DocIterator const & cpit, bool output_active,
3984                                                         UpdateType utype) const
3985 {
3986         DocIterator dit = cpit;
3987         dit.forwardPos();
3988         size_t const end = dit.nargs();
3989         for ( ; dit.idx() < end; dit.top().forwardIdx())
3990                 cell(dit.idx())->addToToc(dit, output_active, utype);
3991 }
3992
3993
3994 bool InsetTabular::hitSelectRow(BufferView const & bv, int x) const
3995 {
3996         int const x0 = xo(bv) + ADD_TO_TABULAR_WIDTH;
3997         return x < x0 || x > x0 + tabular.width();
3998 }
3999
4000
4001 bool InsetTabular::hitSelectColumn(BufferView const & bv, int y) const
4002 {
4003         int const y0 = yo(bv) - tabular.rowAscent(0) + tabular.offsetVAlignment();
4004         // FIXME: using ADD_TO_TABULAR_WIDTH is not really correct since
4005         // there is no margin added vertically to tabular insets.
4006         // However, it works for now.
4007         return y < y0 + ADD_TO_TABULAR_WIDTH || y > y0 + tabular.height() - ADD_TO_TABULAR_WIDTH;
4008 }
4009
4010
4011 bool InsetTabular::clickable(BufferView const & bv, int x, int y) const
4012 {
4013         return hitSelectRow(bv, x) || hitSelectColumn(bv, y);
4014 }
4015
4016
4017 void InsetTabular::doDispatch(Cursor & cur, FuncRequest & cmd)
4018 {
4019         LYXERR(Debug::DEBUG, "# InsetTabular::doDispatch: cmd: " << cmd
4020                              << "\n  cur:" << cur);
4021         CursorSlice sl = cur.top();
4022         Cursor & bvcur = cur.bv().cursor();
4023
4024         FuncCode const act = cmd.action();
4025
4026         switch (act) {
4027
4028         case LFUN_MOUSE_PRESS: {
4029                 //lyxerr << "# InsetTabular::MousePress\n" << cur.bv().cursor() << endl;
4030                 // select row
4031                 if (hitSelectRow(cur.bv(), cmd.x())) {
4032                         row_type r = rowFromY(cur, cmd.y());
4033                         cur.idx() = tabular.getFirstCellInRow(r);
4034                         cur.pit() = 0;
4035                         cur.pos() = 0;
4036                         cur.resetAnchor();
4037                         cur.idx() = tabular.getLastCellInRow(r);
4038                         cur.pit() = cur.lastpit();
4039                         cur.pos() = cur.lastpos();
4040                         cur.selection(true);
4041                         bvcur = cur;
4042                         rowselect_ = true;
4043                         break;
4044                 }
4045                 // select column
4046                 if (hitSelectColumn(cur.bv(), cmd.y())) {
4047                         col_type c = columnFromX(cur, cmd.x());
4048                         cur.idx() = tabular.cellIndex(0, c);
4049                         cur.pit() = 0;
4050                         cur.pos() = 0;
4051                         cur.resetAnchor();
4052                         cur.idx() = tabular.cellIndex(tabular.nrows() - 1, c);
4053                         cur.pit() = cur.lastpit();
4054                         cur.pos() = cur.lastpos();
4055                         cur.selection(true);
4056                         bvcur = cur;
4057                         colselect_ = true;
4058                         break;
4059                 }
4060                 // do not reset cursor/selection if we have selected
4061                 // some cells (bug 2715).
4062                 if (cmd.button() == mouse_button::button3
4063                     && &bvcur.selBegin().inset() == this
4064                     && bvcur.selIsMultiCell())
4065                         ;
4066                 else
4067                         // Let InsetTableCell do it
4068                         cell(cur.idx())->dispatch(cur, cmd);
4069                 break;
4070         }
4071         case LFUN_MOUSE_MOTION:
4072                 //lyxerr << "# InsetTabular::MouseMotion\n" << bvcur << endl;
4073                 if (cmd.button() == mouse_button::button1) {
4074                         // only accept motions to places not deeper nested than the real anchor
4075                         if (!bvcur.realAnchor().hasPart(cur)) {
4076                                 cur.undispatched();
4077                                 break;
4078                         }
4079                         // select (additional) row
4080                         if (rowselect_) {
4081                                 row_type r = rowFromY(cur, cmd.y());
4082                                 cur.idx() = tabular.getLastCellInRow(r);
4083                                 // we need to reset the cursor's pit and pos now, as the old ones
4084                                 // may no longer be valid.
4085                                 cur.pit() = 0;
4086                                 cur.pos() = 0;
4087                                 bvcur.setCursor(cur);
4088                                 bvcur.selection(true);
4089                                 break;
4090                         }
4091                         // select (additional) column
4092                         if (colselect_) {
4093                                 col_type c = columnFromX(cur, cmd.x());
4094                                 cur.idx() = tabular.cellIndex(tabular.nrows() - 1, c);
4095                                 // we need to reset the cursor's pit and pos now, as the old ones
4096                                 // may no longer be valid.
4097                                 cur.pit() = 0;
4098                                 cur.pos() = 0;
4099                                 bvcur.setCursor(cur);
4100                                 bvcur.selection(true);
4101                                 break;
4102                         }
4103                         // only update if selection changes
4104                         if (bvcur.idx() == cur.idx() &&
4105                                 !(bvcur.realAnchor().idx() == cur.idx() && bvcur.pos() != cur.pos()))
4106                                 cur.noScreenUpdate();
4107                         setCursorFromCoordinates(cur, cmd.x(), cmd.y());
4108                         bvcur.setCursor(cur);
4109                         bvcur.selection(true);
4110                         // if this is a multicell selection, we just set the cursor to
4111                         // the beginning of the cell's text.
4112                         if (bvcur.selIsMultiCell()) {
4113                                 bvcur.pit() = bvcur.lastpit();
4114                                 bvcur.pos() = bvcur.lastpos();
4115                         }
4116                 }
4117                 break;
4118
4119         case LFUN_MOUSE_RELEASE:
4120                 rowselect_ = false;
4121                 colselect_ = false;
4122                 break;
4123
4124         case LFUN_CELL_BACKWARD:
4125                 movePrevCell(cur);
4126                 cur.selection(false);
4127                 break;
4128
4129         case LFUN_CELL_FORWARD:
4130                 moveNextCell(cur);
4131                 cur.selection(false);
4132                 break;
4133
4134         case LFUN_CHAR_FORWARD_SELECT:
4135         case LFUN_CHAR_FORWARD:
4136         case LFUN_CHAR_BACKWARD_SELECT:
4137         case LFUN_CHAR_BACKWARD:
4138         case LFUN_CHAR_RIGHT_SELECT:
4139         case LFUN_CHAR_RIGHT:
4140         case LFUN_CHAR_LEFT_SELECT:
4141         case LFUN_CHAR_LEFT:
4142         case LFUN_WORD_FORWARD:
4143         case LFUN_WORD_FORWARD_SELECT:
4144         case LFUN_WORD_BACKWARD:
4145         case LFUN_WORD_BACKWARD_SELECT:
4146         case LFUN_WORD_RIGHT:
4147         case LFUN_WORD_RIGHT_SELECT:
4148         case LFUN_WORD_LEFT:
4149         case LFUN_WORD_LEFT_SELECT: {
4150                 // determine whether we move to next or previous cell, where to enter
4151                 // the new cell from, and which command to "finish" (i.e., exit the
4152                 // inset) with:
4153                 bool next_cell;
4154                 EntryDirection entry_from = ENTRY_DIRECTION_IGNORE;
4155                 FuncCode finish_lfun;
4156
4157                 if (act == LFUN_CHAR_FORWARD
4158                                 || act == LFUN_CHAR_FORWARD_SELECT
4159                                 || act == LFUN_WORD_FORWARD
4160                                 || act == LFUN_WORD_FORWARD_SELECT) {
4161                         next_cell = true;
4162                         finish_lfun = LFUN_FINISHED_FORWARD;
4163                 }
4164                 else if (act == LFUN_CHAR_BACKWARD
4165                                 || act == LFUN_CHAR_BACKWARD_SELECT
4166                                 || act == LFUN_WORD_BACKWARD
4167                                 || act == LFUN_WORD_BACKWARD_SELECT) {
4168                         next_cell = false;
4169                         finish_lfun = LFUN_FINISHED_BACKWARD;
4170                 }
4171                 // LEFT or RIGHT commands --- the interpretation will depend on the
4172                 // table's direction.
4173                 else {
4174                         bool const right = act == LFUN_CHAR_RIGHT
4175                                 || act == LFUN_CHAR_RIGHT_SELECT
4176                                 || act == LFUN_WORD_RIGHT
4177                                 || act == LFUN_WORD_RIGHT_SELECT;
4178                         next_cell = isRightToLeft(cur) != right;
4179
4180                         if (lyxrc.visual_cursor)
4181                                 entry_from = right ? ENTRY_DIRECTION_LEFT:ENTRY_DIRECTION_RIGHT;
4182
4183                         finish_lfun = right ? LFUN_FINISHED_RIGHT : LFUN_FINISHED_LEFT;
4184                 }
4185
4186                 bool const select =     act == LFUN_CHAR_FORWARD_SELECT
4187                     || act == LFUN_CHAR_BACKWARD_SELECT
4188                     || act == LFUN_CHAR_RIGHT_SELECT
4189                     || act == LFUN_CHAR_LEFT_SELECT
4190                         || act == LFUN_WORD_FORWARD_SELECT
4191                         || act == LFUN_WORD_RIGHT_SELECT
4192                         || act == LFUN_WORD_BACKWARD_SELECT
4193                         || act == LFUN_WORD_LEFT_SELECT;
4194
4195                 // If we have a multicell selection or we're
4196                 // not doing some LFUN_*_SELECT thing anyway...
4197                 if (!cur.selIsMultiCell() || !select) {
4198                         col_type const c = tabular.cellColumn(cur.idx());
4199                         row_type const r = tabular.cellRow(cur.idx());
4200                         // Are we trying to select the whole cell and is the whole cell
4201                         // not yet selected?
4202                         bool const select_whole = select && !isCellSelected(cur, r, c) &&
4203                                 ((next_cell && cur.pit() == cur.lastpit()
4204                                 && cur.pos() == cur.lastpos())
4205                                 || (!next_cell && cur.pit() == 0 && cur.pos() == 0));
4206
4207                         bool const empty_cell = cur.lastpos() == 0 && cur.lastpit() == 0;
4208
4209                         // ...try to dispatch to the cell's inset.
4210                         cell(cur.idx())->dispatch(cur, cmd);
4211
4212                         // When we already have a selection we want to select the whole cell
4213                         // before going to the next cell.
4214                         if (select_whole && !empty_cell){
4215                                 getText(cur.idx())->selectAll(cur);
4216                                 cur.dispatched();
4217                                 cur.screenUpdateFlags(Update::Force | Update::FitCursor);
4218                                 break;
4219                         }
4220
4221                         // FIXME: When we support the selection of an empty cell, remove
4222                         // the !empty_cell from this condition. For now we jump to the next
4223                         // cell if the current cell is empty.
4224                         if (cur.result().dispatched() && !empty_cell)
4225                                 break;
4226                 }
4227
4228                 // move to next/prev cell, as appropriate
4229                 // note that we will always do this if we're selecting and we have
4230                 // a multicell selection
4231                 LYXERR(Debug::RTL, "entering " << (next_cell ? "next" : "previous")
4232                         << " cell from: " << int(entry_from));
4233                 if (next_cell)
4234                         moveNextCell(cur, entry_from);
4235                 else
4236                         movePrevCell(cur, entry_from);
4237                 // if we're exiting the table, call the appropriate FINISHED lfun
4238                 if (sl == cur.top()) {
4239                         cmd = FuncRequest(finish_lfun);
4240                         cur.undispatched();
4241                 } else
4242                         cur.dispatched();
4243
4244                 cur.screenUpdateFlags(Update::Force | Update::FitCursor);
4245                 break;
4246
4247         }
4248
4249         case LFUN_DOWN_SELECT:
4250         case LFUN_DOWN:
4251                 if (!(cur.selection() && cur.selIsMultiCell()))
4252                         cell(cur.idx())->dispatch(cur, cmd);
4253
4254                 cur.dispatched(); // override the cell's decision
4255                 if (sl == cur.top()) {
4256                         // if our Text didn't do anything to the cursor
4257                         // then we try to put the cursor into the cell below
4258                         // setting also the right targetX.
4259                         cur.selHandle(act == LFUN_DOWN_SELECT);
4260                         if (tabular.cellRow(cur.idx()) != tabular.nrows() - 1) {
4261                                 int const xtarget = cur.targetX();
4262                                 // WARNING: Once cur.idx() has been reset, the cursor is in
4263                                 // an inconsistent state until pos() has been set. Be careful
4264                                 // what you do with it!
4265                                 cur.idx() = tabular.cellBelow(cur.idx());
4266                                 cur.pit() = 0;
4267                                 TextMetrics const & tm =
4268                                         cur.bv().textMetrics(cell(cur.idx())->getText(0));
4269                                 cur.pos() = tm.x2pos(cur.pit(), 0, xtarget);
4270                                 cur.setCurrentFont();
4271                         }
4272                 }
4273                 if (sl == cur.top()) {
4274                         // we trick it to go to forward after leaving the
4275                         // tabular.
4276                         cmd = FuncRequest(LFUN_FINISHED_FORWARD);
4277                         cur.undispatched();
4278                 }
4279                 if (cur.selIsMultiCell()) {
4280                         cur.pit() = cur.lastpit();
4281                         cur.pos() = cur.lastpos();
4282                         cur.setCurrentFont();
4283                         cur.screenUpdateFlags(Update::Force | Update::FitCursor);
4284                         return;
4285                 }
4286                 cur.screenUpdateFlags(Update::Force | Update::FitCursor);
4287                 break;
4288
4289         case LFUN_UP_SELECT:
4290         case LFUN_UP:
4291                 if (!(cur.selection() && cur.selIsMultiCell()))
4292                         cell(cur.idx())->dispatch(cur, cmd);
4293                 cur.dispatched(); // override the cell's decision
4294                 if (sl == cur.top()) {
4295                         // if our Text didn't do anything to the cursor
4296                         // then we try to put the cursor into the cell above
4297                         // setting also the right targetX.
4298                         cur.selHandle(act == LFUN_UP_SELECT);
4299                         if (tabular.cellRow(cur.idx()) != 0) {
4300                                 int const xtarget = cur.targetX();
4301                                 // WARNING: Once cur.idx() has been reset, the cursor is in
4302                                 // an inconsistent state until pos() has been set. Be careful
4303                                 // what you do with it!
4304                                 cur.idx() = tabular.cellAbove(cur.idx());
4305                                 cur.pit() = cur.lastpit();
4306                                 Text const * text = cell(cur.idx())->getText(0);
4307                                 TextMetrics const & tm = cur.bv().textMetrics(text);
4308                                 ParagraphMetrics const & pm =
4309                                         tm.parMetrics(cur.lastpit());
4310                                 cur.pos() = tm.x2pos(cur.pit(), pm.rows().size()-1, xtarget);
4311                                 cur.setCurrentFont();
4312                         }
4313                 }
4314                 if (sl == cur.top()) {
4315                         cmd = FuncRequest(LFUN_UP);
4316                         cur.undispatched();
4317                 }
4318                 if (cur.selIsMultiCell()) {
4319                         cur.pit() = 0;
4320                         cur.pos() = cur.lastpos();
4321                         cur.setCurrentFont();
4322                         cur.screenUpdateFlags(Update::Force | Update::FitCursor);
4323                         return;
4324                 }
4325                 cur.screenUpdateFlags(Update::Force | Update::FitCursor);
4326                 break;
4327
4328         case LFUN_LAYOUT_TABULAR:
4329                 cur.bv().showDialog("tabular");
4330                 break;
4331
4332         case LFUN_INSET_MODIFY:
4333                 // we come from the dialog
4334                 if (cmd.getArg(0) == "tabular")
4335                         tabularFeatures(cur, cmd.getLongArg(1));
4336                 else
4337                         cur.undispatched();
4338                 break;
4339
4340         case LFUN_TABULAR_FEATURE:
4341                 tabularFeatures(cur, to_utf8(cmd.argument()));
4342                 break;
4343
4344         // insert file functions
4345         case LFUN_FILE_INSERT_PLAINTEXT_PARA:
4346         case LFUN_FILE_INSERT_PLAINTEXT:
4347                 // FIXME UNICODE
4348                 if (FileName::isAbsolute(to_utf8(cmd.argument()))) {
4349                         docstring const tmpstr = cur.bv().contentsOfPlaintextFile(
4350                                 FileName(to_utf8(cmd.argument())));
4351                         if (tmpstr.empty())
4352                                 break;
4353                         cur.recordUndoInset();
4354                         if (insertPlaintextString(cur.bv(), tmpstr, false)) {
4355                                 // content has been replaced,
4356                                 // so cursor might be invalid
4357                                 cur.pos() = cur.lastpos();
4358                                 cur.pit() = cur.lastpit();
4359                                 bvcur.setCursor(cur);
4360                         } else
4361                                 cur.undispatched();
4362                 }
4363                 break;
4364
4365         case LFUN_CUT:
4366                 if (cur.selIsMultiCell()) {
4367                         if (copySelection(cur)) {
4368                                 cur.recordUndoInset();
4369                                 cutSelection(cur);
4370                         }
4371                 } else
4372                         cell(cur.idx())->dispatch(cur, cmd);
4373                 break;
4374
4375         case LFUN_SELF_INSERT:
4376                 if (cur.selIsMultiCell()) {
4377                         cur.recordUndoInset();
4378                         cutSelection(cur);
4379                         BufferView * bv = &cur.bv();
4380                         docstring::const_iterator cit = cmd.argument().begin();
4381                         docstring::const_iterator const end = cmd.argument().end();
4382                         for (; cit != end; ++cit)
4383                                 bv->translateAndInsert(*cit, getText(cur.idx()), cur);
4384
4385                         cur.resetAnchor();
4386                         bv->bookmarkEditPosition();
4387                 } else
4388                         cell(cur.idx())->dispatch(cur, cmd);
4389                 break;
4390
4391         case LFUN_CHAR_DELETE_BACKWARD:
4392         case LFUN_CHAR_DELETE_FORWARD:
4393                 if (cur.selIsMultiCell()) {
4394                         cur.recordUndoInset();
4395                         cutSelection(cur);
4396                 } else
4397                         cell(cur.idx())->dispatch(cur, cmd);
4398                 break;
4399
4400         case LFUN_COPY:
4401                 if (!cur.selection())
4402                         break;
4403                 if (cur.selIsMultiCell()) {
4404                         cur.finishUndo();
4405                         copySelection(cur);
4406                 } else
4407                         cell(cur.idx())->dispatch(cur, cmd);
4408                 break;
4409
4410         case LFUN_CLIPBOARD_PASTE:
4411         case LFUN_PRIMARY_SELECTION_PASTE: {
4412                 docstring const clip = (act == LFUN_CLIPBOARD_PASTE) ?
4413                         theClipboard().getAsText(Clipboard::PlainTextType) :
4414                         theSelection().get();
4415                 if (clip.empty())
4416                         break;
4417                 // pass to InsertPlaintextString, but
4418                 // only if we have multi-cell content
4419                 if (clip.find_first_of(from_ascii("\t\n")) != docstring::npos) {
4420                         cur.recordUndoInset();
4421                         if (insertPlaintextString(cur.bv(), clip, false)) {
4422                                 // content has been replaced,
4423                                 // so cursor might be invalid
4424                                 cur.pos() = cur.lastpos();
4425                                 cur.pit() = cur.lastpit();
4426                                 bvcur.setCursor(cur);
4427                                 break;
4428                         }
4429                 }
4430                 // Let the cell handle normal text
4431                 cell(cur.idx())->dispatch(cur, cmd);
4432                 break;
4433         }
4434
4435         case LFUN_PASTE:
4436                 if (!tabularStackDirty()) {
4437                         if (!cur.selIsMultiCell())
4438                                 cell(cur.idx())->dispatch(cur, cmd);
4439                         break;
4440                 }
4441                 if (theClipboard().isInternal()) {
4442                         cur.recordUndoInset();
4443                         pasteClipboard(cur);
4444                 }
4445                 break;
4446
4447         case LFUN_FONT_EMPH:
4448         case LFUN_FONT_BOLD:
4449         case LFUN_FONT_BOLDSYMBOL:
4450         case LFUN_FONT_ROMAN:
4451         case LFUN_FONT_NOUN:
4452         case LFUN_FONT_ITAL:
4453         case LFUN_FONT_FRAK:
4454         case LFUN_FONT_TYPEWRITER:
4455         case LFUN_FONT_SANS:
4456         case LFUN_TEXTSTYLE_APPLY:
4457         case LFUN_TEXTSTYLE_UPDATE:
4458         case LFUN_FONT_SIZE:
4459         case LFUN_FONT_UNDERLINE:
4460         case LFUN_FONT_STRIKEOUT:
4461         case LFUN_FONT_UNDERUNDERLINE:
4462         case LFUN_FONT_UNDERWAVE:
4463         case LFUN_LANGUAGE:
4464         case LFUN_PARAGRAPH_PARAMS_APPLY:
4465         case LFUN_PARAGRAPH_PARAMS:
4466         case LFUN_WORD_CAPITALIZE:
4467         case LFUN_WORD_UPCASE:
4468         case LFUN_WORD_LOWCASE:
4469         case LFUN_CHARS_TRANSPOSE:
4470                 if (cur.selIsMultiCell()) {
4471                         row_type rs, re;
4472                         col_type cs, ce;
4473                         getSelection(cur, rs, re, cs, ce);
4474                         Cursor tmpcur = cur;
4475                         for (row_type r = rs; r <= re; ++r) {
4476                                 for (col_type c = cs; c <= ce; ++c) {
4477                                         // cursor follows cell:
4478                                         tmpcur.idx() = tabular.cellIndex(r, c);
4479                                         // select this cell only:
4480                                         tmpcur.pit() = 0;
4481                                         tmpcur.pos() = 0;
4482                                         tmpcur.resetAnchor();
4483                                         tmpcur.pit() = tmpcur.lastpit();
4484                                         tmpcur.pos() = tmpcur.top().lastpos();
4485                                         tmpcur.setCursor(tmpcur);
4486                                         tmpcur.setSelection();
4487                                         cell(tmpcur.idx())->dispatch(tmpcur, cmd);
4488                                 }
4489                         }
4490                         break;
4491                 } else {
4492                         cell(cur.idx())->dispatch(cur, cmd);
4493                         break;
4494                 }
4495
4496         case LFUN_INSET_SETTINGS:
4497                 // relay this lfun to Inset, not to the cell.
4498                 Inset::doDispatch(cur, cmd);
4499                 break;
4500
4501         default:
4502                 // we try to handle this event in the insets dispatch function.
4503                 cell(cur.idx())->dispatch(cur, cmd);
4504                 break;
4505         }
4506 }
4507
4508
4509 bool InsetTabular::getFeatureStatus(Cursor & cur, string const & s,
4510                       string const & argument, FuncStatus & status) const
4511 {
4512
4513                 int action = Tabular::LAST_ACTION;
4514                 int i = 0;
4515                 for (; tabularFeature[i].action != Tabular::LAST_ACTION; ++i) {
4516                         if (tabularFeature[i].feature == s) {
4517                                 action = tabularFeature[i].action;
4518                                 break;
4519                         }
4520                 }
4521                 if (action == Tabular::LAST_ACTION) {
4522                         status.clear();
4523                         status.setUnknown(true);
4524                         return true;
4525                 }
4526
4527                 row_type sel_row_start = 0;
4528                 row_type sel_row_end = 0;
4529                 col_type sel_col_start = 0;
4530                 col_type sel_col_end = 0;
4531                 Tabular::ltType dummyltt;
4532                 bool flag = true;
4533
4534                 getSelection(cur, sel_row_start, sel_row_end, sel_col_start, sel_col_end);
4535
4536                 switch (action) {
4537                 case Tabular::SET_PWIDTH:
4538                 case Tabular::SET_MPWIDTH:
4539                 case Tabular::SET_SPECIAL_COLUMN:
4540                 case Tabular::SET_SPECIAL_MULTICOLUMN:
4541                 case Tabular::APPEND_ROW:
4542                 case Tabular::APPEND_COLUMN:
4543                 case Tabular::DELETE_ROW:
4544                 case Tabular::DELETE_COLUMN:
4545                 case Tabular::COPY_ROW:
4546                 case Tabular::COPY_COLUMN:
4547                 case Tabular::SET_TOP_SPACE:
4548                 case Tabular::SET_BOTTOM_SPACE:
4549                 case Tabular::SET_INTERLINE_SPACE:
4550                         status.clear();
4551                         return true;
4552
4553                 case Tabular::SET_TABULAR_WIDTH:
4554                         status.setEnabled(!tabular.rotate &&  !tabular.is_long_tabular
4555                                 && tabular.tabular_valignment == Tabular::LYX_VALIGN_MIDDLE);
4556                         break;
4557
4558                 case Tabular::MOVE_COLUMN_RIGHT:
4559                 case Tabular::MOVE_COLUMN_LEFT:
4560                 case Tabular::MOVE_ROW_DOWN:
4561                 case Tabular::MOVE_ROW_UP: {
4562                         if (cur.selection()) {
4563                                 status.message(_("Selections not supported."));
4564                                 status.setEnabled(false);
4565                                 break;
4566                         }
4567
4568                         if ((action == Tabular::MOVE_COLUMN_RIGHT &&
4569                                 tabular.ncols() == tabular.cellColumn(cur.idx()) + 1) ||
4570                             (action == Tabular::MOVE_COLUMN_LEFT &&
4571                                 tabular.cellColumn(cur.idx()) == 0) ||
4572                             (action == Tabular::MOVE_ROW_DOWN &&
4573                                 tabular.nrows() == tabular.cellRow(cur.idx()) + 1) ||
4574                             (action == Tabular::MOVE_ROW_UP &&
4575                                 tabular.cellRow(cur.idx()) == 0)) {
4576                                         status.setEnabled(false);
4577                                         break;
4578                         }
4579
4580                         if (action == Tabular::MOVE_COLUMN_RIGHT ||
4581                             action == Tabular::MOVE_COLUMN_LEFT) {
4582                                 if (tabular.hasMultiColumn(tabular.cellColumn(cur.idx())) ||
4583                                     tabular.hasMultiColumn(tabular.cellColumn(cur.idx()) +
4584                                         (action == Tabular::MOVE_COLUMN_RIGHT ? 1 : -1))) {
4585                                         status.message(_("Multi-column in current or"
4586                                                          " destination column."));
4587                                         status.setEnabled(false);
4588                                         break;
4589                                 }
4590                         }
4591
4592                         if (action == Tabular::MOVE_ROW_DOWN ||
4593                             action == Tabular::MOVE_ROW_UP) {
4594                                 if (tabular.hasMultiRow(tabular.cellRow(cur.idx())) ||
4595                                     tabular.hasMultiRow(tabular.cellRow(cur.idx()) +
4596                                         (action == Tabular::MOVE_ROW_DOWN ? 1 : -1))) {
4597                                         status.message(_("Multi-row in current or"
4598                                                          " destination row."));
4599                                         status.setEnabled(false);
4600                                         break;
4601                                 }
4602                         }
4603
4604                         status.setEnabled(true);
4605                         break;
4606                 }
4607
4608                 case Tabular::SET_DECIMAL_POINT:
4609                         status.setEnabled(
4610                                 tabular.getAlignment(cur.idx()) == LYX_ALIGN_DECIMAL);
4611                         break;
4612
4613                 case Tabular::SET_MULTICOLUMN:
4614                 case Tabular::UNSET_MULTICOLUMN:
4615                 case Tabular::MULTICOLUMN:
4616                         // If a row is set as longtable caption, it must not be allowed
4617                         // to unset that this row is a multicolumn.
4618                         status.setEnabled(sel_row_start == sel_row_end
4619                                 && !tabular.ltCaption(tabular.cellRow(cur.idx())));
4620                         status.setOnOff(tabular.isMultiColumn(cur.idx()));
4621                         break;
4622
4623                 case Tabular::SET_MULTIROW:
4624                 case Tabular::UNSET_MULTIROW:
4625                 case Tabular::MULTIROW:
4626                         // If a row is set as longtable caption, it must not be allowed
4627                         // to unset that this row is a multirow.
4628                         status.setEnabled(sel_col_start == sel_col_end
4629                                 && !tabular.ltCaption(tabular.cellRow(cur.idx())));
4630                         status.setOnOff(tabular.isMultiRow(cur.idx()));
4631                         break;
4632
4633                 case Tabular::SET_ALL_LINES:
4634                 case Tabular::UNSET_ALL_LINES:
4635                 case Tabular::SET_BORDER_LINES:
4636                         status.setEnabled(!tabular.ltCaption(tabular.cellRow(cur.idx())));
4637                         break;
4638
4639                 case Tabular::SET_LINE_TOP:
4640                 case Tabular::SET_LINE_BOTTOM:
4641                         status.setEnabled(!tabular.ltCaption(tabular.cellRow(cur.idx())));
4642                         break;
4643
4644                 case Tabular::SET_LINE_LEFT:
4645                 case Tabular::SET_LINE_RIGHT:
4646                         status.setEnabled(!tabular.use_booktabs
4647                                           && !tabular.ltCaption(tabular.cellRow(cur.idx())));
4648                         break;
4649
4650                 case Tabular::TOGGLE_LINE_TOP:
4651                         status.setEnabled(!tabular.ltCaption(tabular.cellRow(cur.idx())));
4652                         status.setOnOff(tabular.topLine(cur.idx()));
4653                         break;
4654
4655                 case Tabular::TOGGLE_LINE_BOTTOM:
4656                         status.setEnabled(!tabular.ltCaption(tabular.cellRow(cur.idx())));
4657                         status.setOnOff(tabular.bottomLine(cur.idx()));
4658                         break;
4659
4660                 case Tabular::TOGGLE_LINE_LEFT:
4661                         status.setEnabled(!tabular.use_booktabs
4662                                           && !tabular.ltCaption(tabular.cellRow(cur.idx())));
4663                         status.setOnOff(tabular.leftLine(cur.idx()));
4664                         break;
4665
4666                 case Tabular::TOGGLE_LINE_RIGHT:
4667                         status.setEnabled(!tabular.use_booktabs
4668                                           && !tabular.ltCaption(tabular.cellRow(cur.idx())));
4669                         status.setOnOff(tabular.rightLine(cur.idx()));
4670                         break;
4671
4672                 // multirow cells only inherit the alignment of the column if the column has
4673                 // no width, otherwise they are left-aligned
4674                 // therefore allow always left but right and center only if there is no width
4675                 case Tabular::M_ALIGN_LEFT:
4676                         flag = false;
4677                 case Tabular::ALIGN_LEFT:
4678                         status.setOnOff(tabular.getAlignment(cur.idx(), flag) == LYX_ALIGN_LEFT);
4679                         break;
4680
4681                 case Tabular::M_ALIGN_RIGHT:
4682                         flag = false;
4683                 case Tabular::ALIGN_RIGHT:
4684                         status.setEnabled(!(tabular.isMultiRow(cur.idx())
4685                                 && !tabular.getPWidth(cur.idx()).zero()));
4686                         status.setOnOff(tabular.getAlignment(cur.idx(), flag) == LYX_ALIGN_RIGHT);
4687                         break;
4688
4689                 case Tabular::M_ALIGN_CENTER:
4690                         flag = false;
4691                 case Tabular::ALIGN_CENTER:
4692                         status.setEnabled(!(tabular.isMultiRow(cur.idx())
4693                                 && !tabular.getPWidth(cur.idx()).zero()));
4694                         status.setOnOff(tabular.getAlignment(cur.idx(), flag) == LYX_ALIGN_CENTER);
4695                         break;
4696
4697                 case Tabular::ALIGN_BLOCK:
4698                         status.setEnabled(!tabular.getPWidth(cur.idx()).zero()
4699                                 && !tabular.isMultiRow(cur.idx()));
4700                         status.setOnOff(tabular.getAlignment(cur.idx(), flag) == LYX_ALIGN_BLOCK);
4701                         break;
4702
4703                 case Tabular::ALIGN_DECIMAL:
4704                         status.setEnabled(!tabular.isMultiRow(cur.idx())
4705                                 && !tabular.isMultiColumn(cur.idx()));
4706                         status.setOnOff(tabular.getAlignment(cur.idx(), true) == LYX_ALIGN_DECIMAL);
4707                         break;
4708
4709                 case Tabular::M_VALIGN_TOP:
4710                         flag = false;
4711                 case Tabular::VALIGN_TOP:
4712                         status.setEnabled(!tabular.getPWidth(cur.idx()).zero()
4713                                 && !tabular.isMultiRow(cur.idx()));
4714                         status.setOnOff(
4715                                 tabular.getVAlignment(cur.idx(), flag) == Tabular::LYX_VALIGN_TOP);
4716                         break;
4717
4718                 case Tabular::M_VALIGN_BOTTOM:
4719                         flag = false;
4720                 case Tabular::VALIGN_BOTTOM:
4721                         status.setEnabled(!tabular.getPWidth(cur.idx()).zero()
4722                                 && !tabular.isMultiRow(cur.idx()));
4723                         status.setOnOff(
4724                                 tabular.getVAlignment(cur.idx(), flag) == Tabular::LYX_VALIGN_BOTTOM);
4725                         break;
4726
4727                 case Tabular::M_VALIGN_MIDDLE:
4728                         flag = false;
4729                 case Tabular::VALIGN_MIDDLE:
4730                         status.setEnabled(!tabular.getPWidth(cur.idx()).zero()
4731                                 && !tabular.isMultiRow(cur.idx()));
4732                         status.setOnOff(
4733                                 tabular.getVAlignment(cur.idx(), flag) == Tabular::LYX_VALIGN_MIDDLE);
4734                         break;
4735
4736                 case Tabular::SET_LONGTABULAR:
4737                 case Tabular::TOGGLE_LONGTABULAR:
4738                         // setting as longtable is not allowed when table is inside a float
4739                         if (cur.innerInsetOfType(FLOAT_CODE) != 0
4740                                 || cur.innerInsetOfType(WRAP_CODE) != 0)
4741                                 status.setEnabled(false);
4742                         else
4743                                 status.setEnabled(true);
4744                         status.setOnOff(tabular.is_long_tabular);
4745                         break;
4746
4747                 case Tabular::UNSET_LONGTABULAR:
4748                         status.setOnOff(!tabular.is_long_tabular);
4749                         break;
4750
4751                 case Tabular::TOGGLE_ROTATE_TABULAR:
4752                 case Tabular::SET_ROTATE_TABULAR:
4753                         status.setOnOff(tabular.rotate != 0);
4754                         break;
4755
4756                 case Tabular::TABULAR_VALIGN_TOP:
4757                         status.setEnabled(tabular.tabular_width.zero());
4758                         status.setOnOff(tabular.tabular_valignment
4759                                 == Tabular::LYX_VALIGN_TOP);
4760                         break;
4761                 case Tabular::TABULAR_VALIGN_MIDDLE:
4762                         status.setEnabled(tabular.tabular_width.zero());
4763                         status.setOnOff(tabular.tabular_valignment
4764                                 == Tabular::LYX_VALIGN_MIDDLE);
4765                         break;
4766                 case Tabular::TABULAR_VALIGN_BOTTOM:
4767                         status.setEnabled(tabular.tabular_width.zero());
4768                         status.setOnOff(tabular.tabular_valignment
4769                                 == Tabular::LYX_VALIGN_BOTTOM);
4770                         break;
4771
4772                 case Tabular::LONGTABULAR_ALIGN_LEFT:
4773                         status.setOnOff(tabular.longtabular_alignment
4774                                 == Tabular::LYX_LONGTABULAR_ALIGN_LEFT);
4775                         break;
4776                 case Tabular::LONGTABULAR_ALIGN_CENTER:
4777                         status.setOnOff(tabular.longtabular_alignment
4778                                 == Tabular::LYX_LONGTABULAR_ALIGN_CENTER);
4779                         break;
4780                 case Tabular::LONGTABULAR_ALIGN_RIGHT:
4781                         status.setOnOff(tabular.longtabular_alignment
4782                                 == Tabular::LYX_LONGTABULAR_ALIGN_RIGHT);
4783                         break;
4784
4785                 case Tabular::UNSET_ROTATE_TABULAR:
4786                         status.setOnOff(tabular.rotate == 0);
4787                         break;
4788
4789                 case Tabular::TOGGLE_ROTATE_CELL:
4790                 case Tabular::SET_ROTATE_CELL:
4791                         status.setOnOff(!oneCellHasRotationState(false,
4792                                 sel_row_start, sel_row_end, sel_col_start, sel_col_end));
4793                         break;
4794
4795                 case Tabular::UNSET_ROTATE_CELL:
4796                         status.setOnOff(!oneCellHasRotationState(true,
4797                                 sel_row_start, sel_row_end, sel_col_start, sel_col_end));
4798                         break;
4799
4800                 case Tabular::SET_USEBOX:
4801                         status.setOnOff(convert<int>(argument) == tabular.getUsebox(cur.idx()));
4802                         break;
4803
4804                 // every row can only be one thing:
4805                 // either a footer or header
4806                 case Tabular::SET_LTFIRSTHEAD:
4807                         status.setEnabled(sel_row_start == sel_row_end);
4808                         status.setOnOff(tabular.getRowOfLTFirstHead(sel_row_start, dummyltt));
4809                         break;
4810
4811                 case Tabular::UNSET_LTFIRSTHEAD:
4812                         status.setEnabled(sel_row_start == sel_row_end);
4813                         status.setOnOff(!tabular.getRowOfLTFirstHead(sel_row_start, dummyltt));
4814                         break;
4815
4816                 case Tabular::SET_LTHEAD:
4817                         status.setEnabled(sel_row_start == sel_row_end);
4818                         status.setOnOff(tabular.getRowOfLTHead(sel_row_start, dummyltt));
4819                         break;
4820
4821                 case Tabular::UNSET_LTHEAD:
4822                         status.setEnabled(sel_row_start == sel_row_end);
4823                         status.setOnOff(!tabular.getRowOfLTHead(sel_row_start, dummyltt));
4824                         break;
4825
4826                 case Tabular::SET_LTFOOT:
4827                         status.setEnabled(sel_row_start == sel_row_end);
4828                         status.setOnOff(tabular.getRowOfLTFoot(sel_row_start, dummyltt));
4829                         break;
4830
4831                 case Tabular::UNSET_LTFOOT:
4832                         status.setEnabled(sel_row_start == sel_row_end);
4833                         status.setOnOff(!tabular.getRowOfLTFoot(sel_row_start, dummyltt));
4834                         break;
4835
4836                 case Tabular::SET_LTLASTFOOT:
4837                         status.setEnabled(sel_row_start == sel_row_end);
4838                         status.setOnOff(tabular.getRowOfLTLastFoot(sel_row_start, dummyltt));
4839                         break;
4840
4841                 case Tabular::UNSET_LTLASTFOOT:
4842                         status.setEnabled(sel_row_start == sel_row_end);
4843                         status.setOnOff(!tabular.getRowOfLTLastFoot(sel_row_start, dummyltt));
4844                         break;
4845
4846                 case Tabular::SET_LTNEWPAGE:
4847                         status.setOnOff(tabular.getLTNewPage(sel_row_start));
4848                         break;
4849                 case Tabular::UNSET_LTNEWPAGE:
4850                         status.setOnOff(!tabular.getLTNewPage(sel_row_start));
4851                         break;
4852
4853                 // only one row in head/firsthead/foot/lasthead can be the caption
4854                 // and a multirow cannot be set as caption
4855                 case Tabular::SET_LTCAPTION:
4856                         status.setEnabled(sel_row_start == sel_row_end
4857                                 && (!tabular.getRowOfLTFirstHead(sel_row_start, dummyltt)
4858                                  || !tabular.haveLTCaption(Tabular::CAPTION_FIRSTHEAD))
4859                                 && (!tabular.getRowOfLTHead(sel_row_start, dummyltt)
4860                                  || !tabular.haveLTCaption(Tabular::CAPTION_HEAD))
4861                                 && (!tabular.getRowOfLTFoot(sel_row_start, dummyltt)
4862                                  || !tabular.haveLTCaption(Tabular::CAPTION_FOOT))
4863                                 && (!tabular.getRowOfLTLastFoot(sel_row_start, dummyltt)
4864                                  || !tabular.haveLTCaption(Tabular::CAPTION_LASTFOOT))
4865                                 && !tabular.isMultiRow(sel_row_start));
4866                         status.setOnOff(tabular.ltCaption(sel_row_start));
4867                         break;
4868
4869                 case Tabular::UNSET_LTCAPTION:
4870                         status.setEnabled(sel_row_start == sel_row_end && tabular.ltCaption(sel_row_start));
4871                         break;
4872
4873                 case Tabular::TOGGLE_LTCAPTION:
4874                         status.setEnabled(sel_row_start == sel_row_end && (tabular.ltCaption(sel_row_start)
4875                                 || ((!tabular.getRowOfLTFirstHead(sel_row_start, dummyltt)
4876                                   || !tabular.haveLTCaption(Tabular::CAPTION_FIRSTHEAD))
4877                                  && (!tabular.getRowOfLTHead(sel_row_start, dummyltt)
4878                                   || !tabular.haveLTCaption(Tabular::CAPTION_HEAD))
4879                                  && (!tabular.getRowOfLTFoot(sel_row_start, dummyltt)
4880                                   || !tabular.haveLTCaption(Tabular::CAPTION_FOOT))
4881                                  && (!tabular.getRowOfLTLastFoot(sel_row_start, dummyltt)
4882                                   || !tabular.haveLTCaption(Tabular::CAPTION_LASTFOOT)))));
4883                         status.setOnOff(tabular.ltCaption(sel_row_start));
4884                         break;
4885
4886                 case Tabular::TOGGLE_BOOKTABS:
4887                 case Tabular::SET_BOOKTABS:
4888                         status.setOnOff(tabular.use_booktabs);
4889                         break;
4890
4891                 case Tabular::UNSET_BOOKTABS:
4892                         status.setOnOff(!tabular.use_booktabs);
4893                         break;
4894
4895                 default:
4896                         status.clear();
4897                         status.setEnabled(false);
4898                         break;
4899                 }
4900                 return true;
4901 }
4902
4903
4904 // function sets an object as defined in FuncStatus.h:
4905 // states OK, Unknown, Disabled, On, Off.
4906 bool InsetTabular::getStatus(Cursor & cur, FuncRequest const & cmd,
4907                              FuncStatus & status) const
4908 {
4909         switch (cmd.action()) {
4910         case LFUN_INSET_MODIFY:
4911                 if (cmd.getArg(0) != "tabular")
4912                         break;
4913                 if (cmd.getArg(1) == "for-dialog") {
4914                         // The dialog is asking the status of a command
4915                         if (&cur.inset() != this)
4916                                 break;
4917                         string action = cmd.getArg(2);
4918                         string arg = cmd.getLongArg(3);
4919                         return getFeatureStatus(cur, action, arg, status);
4920                 } else {
4921                         // We always enable the lfun if it is coming from the dialog
4922                         // because the dialog makes sure all the settings are valid,
4923                         // even though the first argument might not be valid now.
4924                         status.setEnabled(true);
4925                         return true;
4926                 }
4927
4928         case LFUN_TABULAR_FEATURE: {
4929                 if (&cur.inset() != this)
4930                         break;
4931                 string action = cmd.getArg(0);
4932                 string arg = cmd.getLongArg(1); 
4933                 return getFeatureStatus(cur, action, arg, status);
4934         }
4935
4936         case LFUN_CAPTION_INSERT: {
4937                 // caption is only allowed in caption cell of longtable
4938                 if (!tabular.ltCaption(tabular.cellRow(cur.idx()))) {
4939                         status.setEnabled(false);
4940                         return true;
4941                 }
4942                 // only standard caption is allowed
4943                 string arg = cmd.getArg(0);
4944                 if (!arg.empty() && arg != "Standard") {
4945                         status.setEnabled(false);
4946                         return true;
4947                 }
4948                 // check if there is already a caption
4949                 bool have_caption = false;
4950                 InsetTableCell itc = InsetTableCell(*tabular.cellInset(cur.idx()));
4951                 ParagraphList::const_iterator pit = itc.paragraphs().begin();
4952                 ParagraphList::const_iterator pend = itc.paragraphs().end();
4953                 for (; pit != pend; ++pit) {
4954                         InsetList::const_iterator it  = pit->insetList().begin();
4955                         InsetList::const_iterator end = pit->insetList().end();
4956                         for (; it != end; ++it) {
4957                                 if (it->inset->lyxCode() == CAPTION_CODE) {
4958                                         have_caption = true;
4959                                         break;
4960                                 }
4961                         }
4962                 }
4963                 status.setEnabled(!have_caption);
4964                 return true;
4965         }
4966
4967         // These are only enabled inside tabular
4968         case LFUN_CELL_BACKWARD:
4969         case LFUN_CELL_FORWARD:
4970                 status.setEnabled(true);
4971                 return true;
4972
4973         // disable these with multiple cells selected
4974         case LFUN_INSET_INSERT:
4975         case LFUN_TABULAR_INSERT:
4976         case LFUN_FLEX_INSERT:
4977         case LFUN_FLOAT_INSERT:
4978         case LFUN_FLOAT_WIDE_INSERT:
4979         case LFUN_FOOTNOTE_INSERT:
4980         case LFUN_MARGINALNOTE_INSERT:
4981         case LFUN_MATH_INSERT:
4982         case LFUN_MATH_MODE:
4983         case LFUN_MATH_MUTATE:
4984         case LFUN_MATH_DISPLAY:
4985         case LFUN_NOTE_INSERT:
4986         case LFUN_ARGUMENT_INSERT:
4987         case LFUN_BOX_INSERT:
4988         case LFUN_BRANCH_INSERT:
4989         case LFUN_PHANTOM_INSERT:
4990         case LFUN_WRAP_INSERT:
4991         case LFUN_PREVIEW_INSERT:
4992         case LFUN_ERT_INSERT: {
4993                 if (cur.selIsMultiCell()) {
4994                         status.setEnabled(false);
4995                         return true;
4996                 } else
4997                         return cell(cur.idx())->getStatus(cur, cmd, status);
4998         }
4999
5000         // disable in non-fixed-width cells
5001         case LFUN_PARAGRAPH_BREAK:
5002                 // multirow does not allow paragraph breaks
5003                 if (tabular.isMultiRow(cur.idx())) {
5004                         status.setEnabled(false);
5005                         return true;
5006                 }
5007                 // Fall back
5008         case LFUN_NEWLINE_INSERT: {
5009                 if (tabular.getPWidth(cur.idx()).zero()) {
5010                         status.setEnabled(false);
5011                         return true;
5012                 } else
5013                         return cell(cur.idx())->getStatus(cur, cmd, status);
5014         }
5015
5016         case LFUN_NEWPAGE_INSERT:
5017                 status.setEnabled(false);
5018                 return true;
5019
5020         case LFUN_PASTE:
5021                 if (tabularStackDirty() && theClipboard().isInternal()) {
5022                         if (cur.selIsMultiCell()) {
5023                                 row_type rs, re;
5024                                 col_type cs, ce;
5025                                 getSelection(cur, rs, re, cs, ce);
5026                                 if (paste_tabular && paste_tabular->ncols() == ce - cs + 1
5027                                           && paste_tabular->nrows() == re - rs + 1)
5028                                         status.setEnabled(true);
5029                                 else {
5030                                         status.setEnabled(false);
5031                                         status.message(_("Selection size should match clipboard content."));
5032                                 }
5033                         } else
5034                                 status.setEnabled(true);
5035                         return true;
5036                 }
5037                 return cell(cur.idx())->getStatus(cur, cmd, status);
5038
5039         case LFUN_INSET_SETTINGS:
5040                 // relay this lfun to Inset, not to the cell.
5041                 return Inset::getStatus(cur, cmd, status);
5042
5043         default:
5044                 // we try to handle this event in the insets dispatch function.
5045                 return cell(cur.idx())->getStatus(cur, cmd, status);
5046         }
5047         return false;
5048 }
5049
5050
5051 Inset::DisplayType InsetTabular::display() const
5052 {
5053                 if (tabular.is_long_tabular) {
5054                         switch (tabular.longtabular_alignment) {
5055                         case Tabular::LYX_LONGTABULAR_ALIGN_LEFT:
5056                                 return AlignLeft;
5057                         case Tabular::LYX_LONGTABULAR_ALIGN_CENTER:
5058                                 return AlignCenter;
5059                         case Tabular::LYX_LONGTABULAR_ALIGN_RIGHT:
5060                                 return AlignRight;
5061                         default:
5062                                 return AlignCenter;
5063                         }
5064                 } else
5065                         return Inline;
5066 }
5067
5068
5069 void InsetTabular::latex(otexstream & os, OutputParams const & runparams) const
5070 {
5071         tabular.latex(os, runparams);
5072 }
5073
5074
5075 int InsetTabular::plaintext(odocstringstream & os,
5076         OutputParams const & runparams, size_t max_length) const
5077 {
5078         os << '\n'; // output table on a new line
5079         int const dp = runparams.linelen > 0 ? runparams.depth : 0;
5080         tabular.plaintext(os, runparams, dp, false, 0, max_length);
5081         return PLAINTEXT_NEWLINE;
5082 }
5083
5084
5085 int InsetTabular::docbook(odocstream & os, OutputParams const & runparams) const
5086 {
5087         int ret = 0;
5088         Inset * master = 0;
5089
5090         // FIXME: Why not pass a proper DocIterator here?
5091 #if 0
5092         // if the table is inside a float it doesn't need the informaltable
5093         // wrapper. Search for it.
5094         for (master = owner(); master; master = master->owner())
5095                 if (master->lyxCode() == FLOAT_CODE)
5096                         break;
5097 #endif
5098
5099         if (!master) {
5100                 os << "<informaltable>";
5101                 ++ret;
5102         }
5103         ret += tabular.docbook(os, runparams);
5104         if (!master) {
5105                 os << "</informaltable>";
5106                 ++ret;
5107         }
5108         return ret;
5109 }
5110
5111
5112 docstring InsetTabular::xhtml(XHTMLStream & xs, OutputParams const & rp) const
5113 {
5114         return tabular.xhtml(xs, rp);
5115 }
5116
5117
5118 void InsetTabular::validate(LaTeXFeatures & features) const
5119 {
5120         tabular.validate(features);
5121         features.useInsetLayout(getLayout());
5122 }
5123
5124
5125 shared_ptr<InsetTableCell const> InsetTabular::cell(idx_type idx) const
5126 {
5127         return tabular.cellInset(idx);
5128 }
5129
5130
5131 shared_ptr<InsetTableCell> InsetTabular::cell(idx_type idx)
5132 {
5133         return tabular.cellInset(idx);
5134 }
5135
5136
5137 void InsetTabular::cursorPos(BufferView const & bv,
5138                 CursorSlice const & sl, bool boundary, int & x, int & y) const
5139 {
5140         cell(sl.idx())->cursorPos(bv, sl, boundary, x, y);
5141
5142         // y offset     correction
5143         y += cellYPos(sl.idx());
5144         y += tabular.textVOffset(sl.idx());
5145         y += tabular.offsetVAlignment();
5146
5147         // x offset correction
5148         x += cellXPos(sl.idx());
5149         x += tabular.textHOffset(sl.idx());
5150         x += ADD_TO_TABULAR_WIDTH;
5151 }
5152
5153
5154 int InsetTabular::dist(BufferView & bv, idx_type const cell, int x, int y) const
5155 {
5156         int xx = 0;
5157         int yy = 0;
5158         Inset const & inset = *tabular.cellInset(cell);
5159         Point o = bv.coordCache().getInsets().xy(&inset);
5160         int const xbeg = o.x_ - tabular.textHOffset(cell);
5161         int const xend = xbeg + tabular.cellWidth(cell);
5162         row_type const row = tabular.cellRow(cell);
5163         int const ybeg = o.y_ - tabular.rowAscent(row)
5164                 - tabular.interRowSpace(row) - tabular.textVOffset(cell);
5165         int const yend = ybeg + tabular.cellHeight(cell);
5166
5167         if (x < xbeg)
5168                 xx = xbeg - x;
5169         else if (x > xend)
5170                 xx = x - xend;
5171
5172         if (y < ybeg)
5173                 yy = ybeg - y;
5174         else if (y > yend)
5175                 yy = y - yend;
5176
5177         //lyxerr << " xbeg=" << xbeg << "  xend=" << xend
5178         //       << " ybeg=" << ybeg << " yend=" << yend
5179         //       << " xx=" << xx << " yy=" << yy
5180         //       << " dist=" << xx + yy << endl;
5181         return xx + yy;
5182 }
5183
5184
5185 Inset * InsetTabular::editXY(Cursor & cur, int x, int y)
5186 {
5187         //lyxerr << "InsetTabular::editXY: " << this << endl;
5188         cur.selection(false);
5189         cur.push(*this);
5190         cur.idx() = getNearestCell(cur.bv(), x, y);
5191         return cur.bv().textMetrics(&cell(cur.idx())->text()).editXY(cur, x, y);
5192 }
5193
5194
5195 void InsetTabular::setCursorFromCoordinates(Cursor & cur, int x, int y) const
5196 {
5197         cur.idx() = getNearestCell(cur.bv(), x, y);
5198         cur.bv().textMetrics(&cell(cur.idx())->text()).setCursorFromCoordinates(cur, x, y);
5199 }
5200
5201
5202 InsetTabular::idx_type InsetTabular::getNearestCell(BufferView & bv, int x, int y) const
5203 {
5204         idx_type idx_min = 0;
5205         int dist_min = numeric_limits<int>::max();
5206         for (idx_type i = 0, n = nargs(); i != n; ++i) {
5207                 if (bv.coordCache().getInsets().has(tabular.cellInset(i).get())) {
5208                         int const d = dist(bv, i, x, y);
5209                         if (d < dist_min) {
5210                                 dist_min = d;
5211                                 idx_min = i;
5212                         }
5213                 }
5214         }
5215         return idx_min;
5216 }
5217
5218
5219 int InsetTabular::cellYPos(idx_type const cell) const
5220 {
5221         row_type row = tabular.cellRow(cell);
5222         int ly = 0;
5223         for (row_type r = 0; r < row; ++r)
5224                 ly += tabular.rowDescent(r) + tabular.rowAscent(r + 1)
5225                         + tabular.interRowSpace(r + 1);
5226         return ly;
5227 }
5228
5229
5230 int InsetTabular::cellXPos(idx_type const cell) const
5231 {
5232         col_type col = tabular.cellColumn(cell);
5233         int lx = 0;
5234         for (col_type c = 0; c < col; ++c)
5235                 lx += tabular.column_info[c].width;
5236         return lx;
5237 }
5238
5239
5240 void InsetTabular::moveNextCell(Cursor & cur, EntryDirection entry_from)
5241 {
5242         row_type const row = tabular.cellRow(cur.idx());
5243         col_type const col = tabular.cellColumn(cur.idx());
5244
5245         if (isRightToLeft(cur)) {
5246                 if (tabular.cellColumn(cur.idx()) == 0) {
5247                         if (row == tabular.nrows() - 1)
5248                                 return;
5249                         cur.idx() = tabular.cellBelow(tabular.getLastCellInRow(row));
5250                 } else {
5251                         if (cur.idx() == 0)
5252                                 return;
5253                         if (col == 0)
5254                                 cur.idx() = tabular.getLastCellInRow(row - 1);
5255                         else
5256                                 cur.idx() = tabular.cellIndex(row, col - 1);
5257                 }
5258         } else {
5259                 if (tabular.isLastCell(cur.idx()))
5260                         return;
5261                 if (cur.idx() == tabular.getLastCellInRow(row))
5262                         cur.idx() = tabular.cellIndex(row + 1, 0);
5263                 else {
5264                         col_type const colnextcell = col + tabular.columnSpan(cur.idx());
5265                         cur.idx() = tabular.cellIndex(row, colnextcell);
5266                 }
5267         }
5268
5269         cur.boundary(false);
5270
5271         if (cur.selIsMultiCell()) {
5272                 cur.pit() = cur.lastpit();
5273                 cur.pos() = cur.lastpos();
5274                 return;
5275         }
5276
5277         cur.pit() = 0;
5278         cur.pos() = 0;
5279
5280         // in visual mode, place cursor at extreme left or right
5281
5282         switch(entry_from) {
5283
5284         case ENTRY_DIRECTION_RIGHT:
5285                 cur.posVisToRowExtremity(false /* !left */);
5286                 break;
5287         case ENTRY_DIRECTION_LEFT:
5288                 cur.posVisToRowExtremity(true /* left */);
5289                 break;
5290         case ENTRY_DIRECTION_IGNORE:
5291                 // nothing to do in this case
5292                 break;
5293
5294         }
5295         cur.setCurrentFont();
5296 }
5297
5298
5299 void InsetTabular::movePrevCell(Cursor & cur, EntryDirection entry_from)
5300 {
5301         row_type const row = tabular.cellRow(cur.idx());
5302         col_type const col = tabular.cellColumn(cur.idx());
5303
5304         if (isRightToLeft(cur)) {
5305                 if (cur.idx() == tabular.getLastCellInRow(row)) {
5306                         if (row == 0)
5307                                 return;
5308                         cur.idx() = tabular.getFirstCellInRow(row);
5309                         cur.idx() = tabular.cellAbove(cur.idx());
5310                 } else {
5311                         if (tabular.isLastCell(cur.idx()))
5312                                 return;
5313                         if (cur.idx() == tabular.getLastCellInRow(row))
5314                                 cur.idx() = tabular.cellIndex(row + 1, 0);
5315                         else
5316                                 cur.idx() = tabular.cellIndex(row, col + 1);
5317                 }
5318         } else {
5319                 if (cur.idx() == 0) // first cell
5320                         return;
5321                 if (col == 0)
5322                         cur.idx() = tabular.getLastCellInRow(row - 1);
5323                 else
5324                         cur.idx() = tabular.cellIndex(row, col - 1);
5325         }
5326
5327         if (cur.selIsMultiCell()) {
5328                 cur.pit() = cur.lastpit();
5329                 cur.pos() = cur.lastpos();
5330                 return;
5331         }
5332
5333         cur.pit() = cur.lastpit();
5334         cur.pos() = cur.lastpos();
5335
5336         // in visual mode, place cursor at extreme left or right
5337
5338         switch(entry_from) {
5339
5340         case ENTRY_DIRECTION_RIGHT:
5341                 cur.posVisToRowExtremity(false /* !left */);
5342                 break;
5343         case ENTRY_DIRECTION_LEFT:
5344                 cur.posVisToRowExtremity(true /* left */);
5345                 break;
5346         case ENTRY_DIRECTION_IGNORE:
5347                 // nothing to do in this case
5348                 break;
5349
5350         }
5351         cur.setCurrentFont();
5352 }
5353
5354
5355 void InsetTabular::tabularFeatures(Cursor & cur, string const & argument)
5356 {
5357         cur.recordUndoInset(this);
5358
5359         istringstream is(argument);
5360         string s;
5361         // Safe guard.
5362         size_t safe_guard = 0;
5363         for (;;) {
5364                 if (is.eof())
5365                         return;
5366                 safe_guard++;
5367                 if (safe_guard > 1000) {
5368                         LYXERR0("parameter max count reached!");
5369                         return;
5370                 }
5371                 is >> s;
5372                 Tabular::Feature action = Tabular::LAST_ACTION;
5373
5374                 size_t i = 0;
5375                 for (; tabularFeature[i].action != Tabular::LAST_ACTION; ++i) {
5376                         if (s != tabularFeature[i].feature)
5377                                 continue;
5378                         action = tabularFeature[i].action;
5379                         break;
5380                 }
5381                 if (action == Tabular::LAST_ACTION) {
5382                         LYXERR0("Feature not found " << s);
5383                         continue;
5384                 }
5385                 string val;
5386                 if (tabularFeature[i].need_value)
5387                         is >> val;
5388                 LYXERR(Debug::DEBUG, "Feature: " << s << "\t\tvalue: " << val);
5389                 tabularFeatures(cur, action, val);
5390         }
5391 }
5392
5393
5394 static void checkLongtableSpecial(Tabular::ltType & ltt,
5395                           string const & special, bool & flag)
5396 {
5397         if (special == "dl_above") {
5398                 ltt.topDL = flag;
5399                 ltt.set = false;
5400         } else if (special == "dl_below") {
5401                 ltt.bottomDL = flag;
5402                 ltt.set = false;
5403         } else if (special == "empty") {
5404                 ltt.empty = flag;
5405                 ltt.set = false;
5406         } else if (flag) {
5407                 ltt.empty = false;
5408                 ltt.set = true;
5409         }
5410 }
5411
5412
5413 bool InsetTabular::oneCellHasRotationState(bool rotated,
5414                 row_type row_start, row_type row_end,
5415                 col_type col_start, col_type col_end) const
5416 {
5417         for (row_type r = row_start; r <= row_end; ++r)
5418                 for (col_type c = col_start; c <= col_end; ++c)
5419                         if (rotated) {
5420                                 if (tabular.getRotateCell(tabular.cellIndex(r, c)) != 0)
5421                                         return true;
5422                         } else {
5423                                 if (tabular.getRotateCell(tabular.cellIndex(r, c)) == 0)
5424                                         return true;
5425                         }
5426         return false;
5427 }
5428
5429
5430 void InsetTabular::tabularFeatures(Cursor & cur,
5431         Tabular::Feature feature, string const & value)
5432 {
5433         col_type sel_col_start;
5434         col_type sel_col_end;
5435         row_type sel_row_start;
5436         row_type sel_row_end;
5437         bool setLines = false;
5438         LyXAlignment setAlign = LYX_ALIGN_LEFT;
5439         Tabular::VAlignment setVAlign = Tabular::LYX_VALIGN_TOP;
5440
5441         switch (feature) {
5442
5443         case Tabular::M_ALIGN_LEFT:
5444         case Tabular::ALIGN_LEFT:
5445                 setAlign = LYX_ALIGN_LEFT;
5446                 break;
5447
5448         case Tabular::M_ALIGN_RIGHT:
5449         case Tabular::ALIGN_RIGHT:
5450                 setAlign = LYX_ALIGN_RIGHT;
5451                 break;
5452
5453         case Tabular::M_ALIGN_CENTER:
5454         case Tabular::ALIGN_CENTER:
5455                 setAlign = LYX_ALIGN_CENTER;
5456                 break;
5457
5458         case Tabular::ALIGN_BLOCK:
5459                 setAlign = LYX_ALIGN_BLOCK;
5460                 break;
5461
5462         case Tabular::ALIGN_DECIMAL:
5463                 setAlign = LYX_ALIGN_DECIMAL;
5464                 break;
5465
5466         case Tabular::M_VALIGN_TOP:
5467         case Tabular::VALIGN_TOP:
5468                 setVAlign = Tabular::LYX_VALIGN_TOP;
5469                 break;
5470
5471         case Tabular::M_VALIGN_BOTTOM:
5472         case Tabular::VALIGN_BOTTOM:
5473                 setVAlign = Tabular::LYX_VALIGN_BOTTOM;
5474                 break;
5475
5476         case Tabular::M_VALIGN_MIDDLE:
5477         case Tabular::VALIGN_MIDDLE:
5478                 setVAlign = Tabular::LYX_VALIGN_MIDDLE;
5479                 break;
5480
5481         default:
5482                 break;
5483         }
5484
5485         getSelection(cur, sel_row_start, sel_row_end, sel_col_start, sel_col_end);
5486         row_type const row = tabular.cellRow(cur.idx());
5487         col_type const column = tabular.cellColumn(cur.idx());
5488         bool flag = true;
5489         Tabular::ltType ltt;
5490
5491         switch (feature) {
5492
5493         case Tabular::SET_TABULAR_WIDTH:
5494                 tabular.setTabularWidth(Length(value));
5495                 break;
5496
5497         case Tabular::SET_PWIDTH: {
5498                 Length const len(value);
5499                 tabular.setColumnPWidth(cur, cur.idx(), len);
5500                 if (len.zero()
5501                     && tabular.getAlignment(cur.idx(), true) == LYX_ALIGN_BLOCK)
5502                         tabularFeatures(cur, Tabular::ALIGN_CENTER, string());
5503                 break;
5504         }
5505
5506         case Tabular::SET_MPWIDTH:
5507                 tabular.setMColumnPWidth(cur, cur.idx(), Length(value));
5508                 break;
5509
5510         case Tabular::SET_MROFFSET:
5511                 tabular.setMROffset(cur, cur.idx(), Length(value));
5512                 break;
5513
5514         case Tabular::SET_SPECIAL_COLUMN:
5515         case Tabular::SET_SPECIAL_MULTICOLUMN:
5516                 if (value == "none")
5517                         tabular.setAlignSpecial(cur.idx(), docstring(), feature);
5518                 else
5519                         tabular.setAlignSpecial(cur.idx(), from_utf8(value), feature);
5520                 break;
5521
5522         case Tabular::APPEND_ROW:
5523                 // append the row into the tabular
5524                 tabular.appendRow(row);
5525                 break;
5526
5527         case Tabular::APPEND_COLUMN:
5528                 // append the column into the tabular
5529                 tabular.appendColumn(column);
5530                 cur.idx() = tabular.cellIndex(row, column);
5531                 break;
5532
5533         case Tabular::DELETE_ROW:
5534                 if (sel_row_end == tabular.nrows() - 1 && sel_row_start != 0) {
5535                         for (col_type c = 0; c < tabular.ncols(); c++)
5536                                 tabular.setBottomLine(tabular.cellIndex(sel_row_start - 1, c),
5537                                         tabular.bottomLine(tabular.cellIndex(sel_row_end, c)));
5538                 }
5539
5540                 for (row_type r = sel_row_start; r <= sel_row_end; ++r)
5541                         tabular.deleteRow(sel_row_start);
5542                 if (sel_row_start >= tabular.nrows())
5543                         --sel_row_start;
5544                 cur.idx() = tabular.cellIndex(sel_row_start, column);
5545                 cur.pit() = 0;
5546                 cur.pos() = 0;
5547                 cur.selection(false);
5548                 break;
5549
5550         case Tabular::DELETE_COLUMN:
5551                 if (sel_col_end == tabular.ncols() - 1 && sel_col_start != 0) {
5552                         for (row_type r = 0; r < tabular.nrows(); r++)
5553                                 tabular.setRightLine(tabular.cellIndex(r, sel_col_start - 1),
5554                                         tabular.rightLine(tabular.cellIndex(r, sel_col_end)));
5555                 }
5556
5557                 if (sel_col_start == 0 && sel_col_end != tabular.ncols() - 1) {
5558                         for (row_type r = 0; r < tabular.nrows(); r++)
5559                                 tabular.setLeftLine(tabular.cellIndex(r, sel_col_end + 1),
5560                                         tabular.leftLine(tabular.cellIndex(r, 0)));
5561                 }
5562
5563                 for (col_type c = sel_col_start; c <= sel_col_end; ++c)
5564                         tabular.deleteColumn(sel_col_start);
5565                 if (sel_col_start >= tabular.ncols())
5566                         --sel_col_start;
5567                 cur.idx() = tabular.cellIndex(row, sel_col_start);
5568                 cur.pit() = 0;
5569                 cur.pos() = 0;
5570                 cur.selection(false);
5571                 break;
5572
5573         case Tabular::COPY_ROW:
5574                 tabular.copyRow(row);
5575                 break;
5576
5577         case Tabular::COPY_COLUMN:
5578                 tabular.copyColumn(column);
5579                 cur.idx() = tabular.cellIndex(row, column);
5580                 break;
5581
5582         case Tabular::MOVE_COLUMN_RIGHT:
5583                 tabular.moveColumn(column, Tabular::RIGHT);
5584                 cur.idx() = tabular.cellIndex(row, column + 1);
5585                 break;
5586
5587         case Tabular::MOVE_COLUMN_LEFT:
5588                 tabular.moveColumn(column, Tabular::LEFT);
5589                 cur.idx() = tabular.cellIndex(row, column - 1);
5590                 break;
5591
5592         case Tabular::MOVE_ROW_DOWN:
5593                 tabular.moveRow(row, Tabular::DOWN);
5594                 cur.idx() = tabular.cellIndex(row + 1, column);
5595                 break;
5596
5597         case Tabular::MOVE_ROW_UP:
5598                 tabular.moveRow(row, Tabular::UP);
5599                 cur.idx() = tabular.cellIndex(row - 1, column);
5600                 break;
5601
5602         case Tabular::SET_LINE_TOP:
5603         case Tabular::TOGGLE_LINE_TOP: {
5604                 bool lineSet = (feature == Tabular::SET_LINE_TOP)
5605                                ? (value == "true") : !tabular.topLine(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.setTopLine(tabular.cellIndex(r, c), lineSet);
5609                 break;
5610         }
5611
5612         case Tabular::SET_LINE_BOTTOM:
5613         case Tabular::TOGGLE_LINE_BOTTOM: {
5614                 bool lineSet = (feature == Tabular::SET_LINE_BOTTOM)
5615                                ? (value == "true") : !tabular.bottomLine(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.setBottomLine(tabular.cellIndex(r, c), lineSet);
5619                 break;
5620         }
5621
5622         case Tabular::SET_LINE_LEFT:
5623         case Tabular::TOGGLE_LINE_LEFT: {
5624                 bool lineSet = (feature == Tabular::SET_LINE_LEFT)
5625                                ? (value == "true") : !tabular.leftLine(cur.idx());
5626                 for (row_type r = sel_row_start; r <= sel_row_end; ++r)
5627                         for (col_type c = sel_col_start; c <= sel_col_end; ++c)
5628                                 tabular.setLeftLine(tabular.cellIndex(r, c), lineSet);
5629                 break;
5630         }
5631
5632         case Tabular::SET_LINE_RIGHT:
5633         case Tabular::TOGGLE_LINE_RIGHT: {
5634                 bool lineSet = (feature == Tabular::SET_LINE_RIGHT)
5635                                ? (value == "true") : !tabular.rightLine(cur.idx());
5636                 for (row_type r = sel_row_start; r <= sel_row_end; ++r)
5637                         for (col_type c = sel_col_start; c <= sel_col_end; ++c)
5638                                 tabular.setRightLine(tabular.cellIndex(r, c), lineSet);
5639                 break;
5640         }
5641
5642         case Tabular::M_ALIGN_LEFT:
5643         case Tabular::M_ALIGN_RIGHT:
5644         case Tabular::M_ALIGN_CENTER:
5645         case Tabular::ALIGN_LEFT:
5646         case Tabular::ALIGN_RIGHT:
5647         case Tabular::ALIGN_CENTER:
5648         case Tabular::ALIGN_BLOCK:
5649         case Tabular::ALIGN_DECIMAL:
5650                 for (row_type r = sel_row_start; r <= sel_row_end; ++r)
5651                         for (col_type c = sel_col_start; c <= sel_col_end; ++c)
5652                                 tabular.setAlignment(tabular.cellIndex(r, c), setAlign,
5653                                 !tabular.getPWidth(c).zero());
5654                 break;
5655
5656         case Tabular::M_VALIGN_TOP:
5657         case Tabular::M_VALIGN_BOTTOM:
5658         case Tabular::M_VALIGN_MIDDLE:
5659                 flag = false;
5660         case Tabular::VALIGN_TOP:
5661         case Tabular::VALIGN_BOTTOM:
5662         case Tabular::VALIGN_MIDDLE:
5663                 for (row_type r = sel_row_start; r <= sel_row_end; ++r)
5664                         for (col_type c = sel_col_start; c <= sel_col_end; ++c)
5665                                 tabular.setVAlignment(tabular.cellIndex(r, c), setVAlign, flag);
5666                 break;
5667
5668         case Tabular::SET_MULTICOLUMN: {
5669                 if (!cur.selection()) {
5670                         // just multicol for one single cell
5671                         // check whether we are completely in a multicol
5672                         if (!tabular.isMultiColumn(cur.idx()))
5673                                 tabular.setMultiColumn(cur.idx(), 1,
5674                                         tabular.rightLine(cur.idx()));
5675                         break;
5676                 }
5677                 // we have a selection so this means we just add all these
5678                 // cells to form a multicolumn cell
5679                 idx_type const s_start = cur.selBegin().idx();
5680                 row_type const col_start = tabular.cellColumn(s_start);
5681                 row_type const col_end = tabular.cellColumn(cur.selEnd().idx());
5682                 cur.idx() = tabular.setMultiColumn(s_start, col_end - col_start + 1,
5683                                                    tabular.rightLine(cur.selEnd().idx()));
5684                 cur.pit() = 0;
5685                 cur.pos() = 0;
5686                 cur.selection(false);
5687                 break;
5688         }
5689
5690         case Tabular::UNSET_MULTICOLUMN: {
5691                 if (!cur.selection()) {
5692                         if (tabular.isMultiColumn(cur.idx()))
5693                                 tabular.unsetMultiColumn(cur.idx());
5694                 }
5695                 break;
5696         }
5697
5698         case Tabular::MULTICOLUMN: {
5699                 if (!cur.selection()) {
5700                         if (tabular.isMultiColumn(cur.idx()))
5701                                 tabularFeatures(cur, Tabular::UNSET_MULTICOLUMN);
5702                         else
5703                                 tabularFeatures(cur, Tabular::SET_MULTICOLUMN);
5704                         break;
5705                 }
5706                 bool merge = false;
5707                 for (col_type c = sel_col_start; c <= sel_col_end; ++c) {
5708                         row_type const r = sel_row_start;
5709                         if (!tabular.isMultiColumn(tabular.cellIndex(r, c))
5710                             || (r > sel_row_start && !tabular.isPartOfMultiColumn(r, c)))
5711                                 merge = true;
5712                 }
5713                 // If the selection contains at least one singlecol cell
5714                 // or multiple multicol cells,
5715                 // we assume the user will merge is to a single multicol
5716                 if (merge)
5717                         tabularFeatures(cur, Tabular::SET_MULTICOLUMN);
5718                 else
5719                         tabularFeatures(cur, Tabular::UNSET_MULTICOLUMN);
5720                 break;
5721         }
5722
5723         case Tabular::SET_MULTIROW: {
5724                 if (!cur.selection()) {
5725                         // just multirow for one single cell
5726                         // check whether we are completely in a multirow
5727                         if (!tabular.isMultiRow(cur.idx()))
5728                                 tabular.setMultiRow(cur.idx(), 1,
5729                                                     tabular.bottomLine(cur.idx()),
5730                                                     tabular.getAlignment(cur.idx()));
5731                         break;
5732                 }
5733                 // we have a selection so this means we just add all this
5734                 // cells to form a multirow cell
5735                 idx_type const s_start = cur.selBegin().idx();
5736                 row_type const row_start = tabular.cellRow(s_start);
5737                 row_type const row_end = tabular.cellRow(cur.selEnd().idx());
5738                 cur.idx() = tabular.setMultiRow(s_start, row_end - row_start + 1,
5739                                                 tabular.bottomLine(cur.selEnd().idx()),
5740                                                 tabular.getAlignment(cur.selEnd().idx()));
5741                 cur.pit() = 0;
5742                 cur.pos() = 0;
5743                 cur.selection(false);
5744                 break;
5745         }
5746
5747         case Tabular::UNSET_MULTIROW: {
5748                 if (!cur.selection()) {
5749                         if (tabular.isMultiRow(cur.idx()))
5750                                 tabular.unsetMultiRow(cur.idx());
5751                 }
5752                 break;
5753         }
5754
5755         case Tabular::MULTIROW: {
5756                 if (!cur.selection()) {
5757                         if (tabular.isMultiRow(cur.idx()))
5758                                 tabularFeatures(cur, Tabular::UNSET_MULTIROW);
5759                         else
5760                                 tabularFeatures(cur, Tabular::SET_MULTIROW);
5761                         break;
5762                 }
5763                 bool merge = false;
5764                 for (row_type r = sel_row_start; r <= sel_row_end; ++r) {
5765                         col_type const c = sel_col_start;
5766                         if (!tabular.isMultiRow(tabular.cellIndex(r, c))
5767                             || (r > sel_row_start && !tabular.isPartOfMultiRow(r, c)))
5768                                 merge = true;
5769                 }
5770                 // If the selection contains at least one singlerow cell
5771                 // or multiple multirow cells,
5772                 // we assume the user will merge is to a single multirow
5773                 if (merge)
5774                         tabularFeatures(cur, Tabular::SET_MULTIROW);
5775                 else
5776                         tabularFeatures(cur, Tabular::UNSET_MULTIROW);
5777                 break;
5778         }
5779
5780         case Tabular::SET_ALL_LINES:
5781                 setLines = true;
5782         case Tabular::UNSET_ALL_LINES:
5783                 for (row_type r = sel_row_start; r <= sel_row_end; ++r)
5784                         for (col_type c = sel_col_start; c <= sel_col_end; ++c) {
5785                                 idx_type const cell = tabular.cellIndex(r, c);
5786                                 tabular.setTopLine(cell, setLines);
5787                                 tabular.setBottomLine(cell, setLines);
5788                                 tabular.setRightLine(cell, setLines);
5789                                 tabular.setLeftLine(cell, setLines);
5790                         }
5791                 break;
5792
5793         case Tabular::SET_BORDER_LINES:
5794                 for (row_type r = sel_row_start; r <= sel_row_end; ++r) {
5795                         tabular.setLeftLine(tabular.cellIndex(r, sel_col_start), true);
5796                         tabular.setRightLine(tabular.cellIndex(r, sel_col_end), true);
5797                 }
5798                 for (col_type c = sel_col_start; c <= sel_col_end; ++c) {
5799                         tabular.setTopLine(tabular.cellIndex(sel_row_start, c), true);
5800                         tabular.setBottomLine(tabular.cellIndex(sel_row_end, c), true);
5801                 }
5802                 break;
5803
5804         case Tabular::TOGGLE_LONGTABULAR:
5805                 if (tabular.is_long_tabular)
5806                         tabularFeatures(cur, Tabular::UNSET_LONGTABULAR);
5807                 else
5808                         tabular.is_long_tabular = true;
5809                 break;
5810
5811         case Tabular::SET_LONGTABULAR:
5812                 tabular.is_long_tabular = true;
5813                 break;
5814
5815         case Tabular::UNSET_LONGTABULAR:
5816                 for (row_type r = 0; r < tabular.nrows(); ++r) {
5817                         if (tabular.ltCaption(r)) {
5818                                 cur.idx() = tabular.cellIndex(r, 0);
5819                                 cur.pit() = 0;
5820                                 cur.pos() = 0;
5821                                 tabularFeatures(cur, Tabular::TOGGLE_LTCAPTION);
5822                         }
5823                 }
5824                 tabular.is_long_tabular = false;
5825                 break;
5826
5827         case Tabular::SET_ROTATE_TABULAR:
5828                 tabular.rotate = convert<int>(value);
5829                 break;
5830
5831         case Tabular::UNSET_ROTATE_TABULAR:
5832                 tabular.rotate = 0;
5833                 break;
5834
5835         case Tabular::TOGGLE_ROTATE_TABULAR:
5836                 // when pressing the rotate button we default to 90° rotation
5837                 tabular.rotate != 0 ? tabular.rotate = 0 : tabular.rotate = 90;
5838                 break;
5839
5840         case Tabular::TABULAR_VALIGN_TOP:
5841                 tabular.tabular_valignment = Tabular::LYX_VALIGN_TOP;
5842                 break;
5843
5844         case Tabular::TABULAR_VALIGN_MIDDLE:
5845                 tabular.tabular_valignment = Tabular::LYX_VALIGN_MIDDLE;
5846                 break;
5847
5848         case Tabular::TABULAR_VALIGN_BOTTOM:
5849                 tabular.tabular_valignment = Tabular::LYX_VALIGN_BOTTOM;
5850                 break;
5851
5852         case Tabular::LONGTABULAR_ALIGN_LEFT:
5853                 tabular.longtabular_alignment = Tabular::LYX_LONGTABULAR_ALIGN_LEFT;
5854                 break;
5855
5856         case Tabular::LONGTABULAR_ALIGN_CENTER:
5857                 tabular.longtabular_alignment = Tabular::LYX_LONGTABULAR_ALIGN_CENTER;
5858                 break;
5859
5860         case Tabular::LONGTABULAR_ALIGN_RIGHT:
5861                 tabular.longtabular_alignment = Tabular::LYX_LONGTABULAR_ALIGN_RIGHT;
5862                 break;
5863
5864
5865
5866         case Tabular::SET_ROTATE_CELL:
5867                 for (row_type r = sel_row_start; r <= sel_row_end; ++r)
5868                         for (col_type c = sel_col_start; c <= sel_col_end; ++c)
5869                                 tabular.setRotateCell(tabular.cellIndex(r, c), convert<int>(value));
5870                 break;
5871
5872         case Tabular::UNSET_ROTATE_CELL:
5873                 for (row_type r = sel_row_start; r <= sel_row_end; ++r)
5874                         for (col_type c = sel_col_start; c <= sel_col_end; ++c)
5875                                 tabular.setRotateCell(tabular.cellIndex(r, c), 0);
5876                 break;
5877
5878         case Tabular::TOGGLE_ROTATE_CELL:
5879                 {
5880                 bool oneNotRotated = oneCellHasRotationState(false,
5881                         sel_row_start, sel_row_end, sel_col_start, sel_col_end);
5882
5883                 for (row_type r = sel_row_start; r <= sel_row_end; ++r)
5884                         for (col_type c = sel_col_start; c <= sel_col_end; ++c) {
5885                                 // when pressing the rotate cell button we default to 90° rotation
5886                                 if (oneNotRotated)
5887                                         tabular.setRotateCell(tabular.cellIndex(r, c), 90);
5888                                 else
5889                                         tabular.setRotateCell(tabular.cellIndex(r, c), 0);
5890                         }
5891                 }
5892                 break;
5893
5894         case Tabular::SET_USEBOX: {
5895                 Tabular::BoxType val = Tabular::BoxType(convert<int>(value));
5896                 if (val == tabular.getUsebox(cur.idx()))
5897                         val = Tabular::BOX_NONE;
5898                 for (row_type r = sel_row_start; r <= sel_row_end; ++r)
5899                         for (col_type c = sel_col_start; c <= sel_col_end; ++c)
5900                                 tabular.setUsebox(tabular.cellIndex(r, c), val);
5901                 break;
5902         }
5903
5904         case Tabular::UNSET_LTFIRSTHEAD:
5905                 flag = false;
5906         case Tabular::SET_LTFIRSTHEAD:
5907                 tabular.getRowOfLTFirstHead(row, ltt);
5908                 checkLongtableSpecial(ltt, value, flag);
5909                 tabular.setLTHead(row, flag, ltt, true);
5910                 break;
5911
5912         case Tabular::UNSET_LTHEAD:
5913                 flag = false;
5914         case Tabular::SET_LTHEAD:
5915                 tabular.getRowOfLTHead(row, ltt);
5916                 checkLongtableSpecial(ltt, value, flag);
5917                 tabular.setLTHead(row, flag, ltt, false);
5918                 break;
5919
5920         case Tabular::UNSET_LTFOOT:
5921                 flag = false;
5922         case Tabular::SET_LTFOOT:
5923                 tabular.getRowOfLTFoot(row, ltt);
5924                 checkLongtableSpecial(ltt, value, flag);
5925                 tabular.setLTFoot(row, flag, ltt, false);
5926                 break;
5927
5928         case Tabular::UNSET_LTLASTFOOT:
5929                 flag = false;
5930         case Tabular::SET_LTLASTFOOT:
5931                 tabular.getRowOfLTLastFoot(row, ltt);
5932                 checkLongtableSpecial(ltt, value, flag);
5933                 tabular.setLTFoot(row, flag, ltt, true);
5934                 break;
5935
5936         case Tabular::UNSET_LTNEWPAGE:
5937                 flag = false;
5938         case Tabular::SET_LTNEWPAGE:
5939                 tabular.setLTNewPage(row, flag);
5940                 break;
5941
5942         case Tabular::SET_LTCAPTION: {
5943                 if (tabular.ltCaption(row))
5944                         break;
5945                 cur.idx() = tabular.setLTCaption(row, true);
5946                 cur.pit() = 0;
5947                 cur.pos() = 0;
5948                 cur.selection(false);
5949                 // If a row is set as caption, then also insert
5950                 // a caption. Otherwise the LaTeX output is broken.
5951                 // Select cell if it is non-empty
5952                 if (cur.lastpos() > 0 || cur.lastpit() > 0)
5953                         lyx::dispatch(FuncRequest(LFUN_INSET_SELECT_ALL));
5954                 lyx::dispatch(FuncRequest(LFUN_CAPTION_INSERT));
5955                 break;
5956         }
5957
5958         case Tabular::UNSET_LTCAPTION: {
5959                 if (!tabular.ltCaption(row))
5960                         break;
5961                 cur.idx() = tabular.setLTCaption(row, false);
5962                 cur.pit() = 0;
5963                 cur.pos() = 0;
5964                 cur.selection(false);
5965                 FuncRequest fr(LFUN_INSET_DISSOLVE, "caption");
5966                 if (lyx::getStatus(fr).enabled())
5967                         lyx::dispatch(fr);
5968                 break;
5969         }
5970
5971         case Tabular::TOGGLE_LTCAPTION: {
5972                 if (tabular.ltCaption(row))
5973                         tabularFeatures(cur, Tabular::UNSET_LTCAPTION);
5974                 else
5975                         tabularFeatures(cur, Tabular::SET_LTCAPTION);
5976                 break;
5977         }
5978
5979         case Tabular::TOGGLE_BOOKTABS:
5980                 tabular.use_booktabs = !tabular.use_booktabs;
5981                 break;
5982
5983         case Tabular::SET_BOOKTABS:
5984                 tabular.use_booktabs = true;
5985                 break;
5986
5987         case Tabular::UNSET_BOOKTABS:
5988                 tabular.use_booktabs = false;
5989                 break;
5990
5991         case Tabular::SET_TOP_SPACE: {
5992                 Length len;
5993                 if (value == "default")
5994                         for (row_type r = sel_row_start; r <= sel_row_end; ++r)
5995                                 tabular.row_info[r].top_space_default = true;
5996                 else if (value == "none")
5997                         for (row_type r = sel_row_start; r <= sel_row_end; ++r) {
5998                                 tabular.row_info[r].top_space_default = false;
5999                                 tabular.row_info[r].top_space = len;
6000                         }
6001                 else if (isValidLength(value, &len))
6002                         for (row_type r = sel_row_start; r <= sel_row_end; ++r) {
6003                                 tabular.row_info[r].top_space_default = false;
6004                                 tabular.row_info[r].top_space = len;
6005                         }
6006                 break;
6007         }
6008
6009         case Tabular::SET_BOTTOM_SPACE: {
6010                 Length len;
6011                 if (value == "default")
6012                         for (row_type r = sel_row_start; r <= sel_row_end; ++r)
6013                                 tabular.row_info[r].bottom_space_default = true;
6014                 else if (value == "none")
6015                         for (row_type r = sel_row_start; r <= sel_row_end; ++r) {
6016                                 tabular.row_info[r].bottom_space_default = false;
6017                                 tabular.row_info[r].bottom_space = len;
6018                         }
6019                 else if (isValidLength(value, &len))
6020                         for (row_type r = sel_row_start; r <= sel_row_end; ++r) {
6021                                 tabular.row_info[r].bottom_space_default = false;
6022                                 tabular.row_info[r].bottom_space = len;
6023                         }
6024                 break;
6025         }
6026
6027         case Tabular::SET_INTERLINE_SPACE: {
6028                 Length len;
6029                 if (value == "default")
6030                         for (row_type r = sel_row_start; r <= sel_row_end; ++r)
6031                                 tabular.row_info[r].interline_space_default = true;
6032                 else if (value == "none")
6033                         for (row_type r = sel_row_start; r <= sel_row_end; ++r) {
6034                                 tabular.row_info[r].interline_space_default = false;
6035                                 tabular.row_info[r].interline_space = len;
6036                         }
6037                 else if (isValidLength(value, &len))
6038                         for (row_type r = sel_row_start; r <= sel_row_end; ++r) {
6039                                 tabular.row_info[r].interline_space_default = false;
6040                                 tabular.row_info[r].interline_space = len;
6041                         }
6042                 break;
6043         }
6044
6045         case Tabular::SET_DECIMAL_POINT:
6046                 for (col_type c = sel_col_start; c <= sel_col_end; ++c)
6047                         tabular.column_info[c].decimal_point = from_utf8(value);
6048                 break;
6049
6050         // dummy stuff just to avoid warnings
6051         case Tabular::LAST_ACTION:
6052                 break;
6053         }
6054 }
6055
6056
6057 bool InsetTabular::copySelection(Cursor & cur)
6058 {
6059         if (!cur.selection())
6060                 return false;
6061
6062         row_type rs, re;
6063         col_type cs, ce;
6064         getSelection(cur, rs, re, cs, ce);
6065
6066         paste_tabular.reset(new Tabular(tabular));
6067
6068         for (row_type r = 0; r < rs; ++r)
6069                 paste_tabular->deleteRow(0);
6070
6071         row_type const rows = re - rs + 1;
6072         while (paste_tabular->nrows() > rows)
6073                 paste_tabular->deleteRow(rows);
6074
6075         for (col_type c = 0; c < cs; ++c)
6076                 paste_tabular->deleteColumn(0);
6077
6078         col_type const columns = ce - cs + 1;
6079         while (paste_tabular->ncols() > columns)
6080                 paste_tabular->deleteColumn(columns);
6081
6082         paste_tabular->setBuffer(tabular.buffer());
6083
6084         odocstringstream os;
6085         OutputParams const runparams(0);
6086         paste_tabular->plaintext(os, runparams, 0, true, '\t', INT_MAX);
6087         // Needed for the "Edit->Paste recent" menu and the system clipboard.
6088         cap::copySelection(cur, os.str());
6089
6090         // mark tabular stack dirty
6091         // FIXME: this is a workaround for bug 1919. Should be removed for 1.5,
6092         // when we (hopefully) have a one-for-all paste mechanism.
6093         // This must be called after cap::copySelection.
6094         dirtyTabularStack(true);
6095
6096         return true;
6097 }
6098
6099
6100 bool InsetTabular::pasteClipboard(Cursor & cur)
6101 {
6102         if (!paste_tabular)
6103                 return false;
6104         col_type actcol = tabular.cellColumn(cur.idx());
6105         row_type actrow = tabular.cellRow(cur.idx());
6106
6107         if (cur.selIsMultiCell()) {
6108                 row_type re;
6109                 col_type ce;
6110                 getSelection(cur, actrow, re, actcol, ce);
6111         }
6112
6113         for (row_type r1 = 0, r2 = actrow;
6114              r1 < paste_tabular->nrows() && r2 < tabular.nrows();
6115              ++r1, ++r2) {
6116                 for (col_type c1 = 0, c2 = actcol;
6117                     c1 < paste_tabular->ncols() && c2 < tabular.ncols();
6118                     ++c1, ++c2) {
6119                         if (paste_tabular->isPartOfMultiColumn(r1, c1) &&
6120                               tabular.isPartOfMultiColumn(r2, c2))
6121                                 continue;
6122                         if (paste_tabular->isPartOfMultiColumn(r1, c1)) {
6123                                 --c2;
6124                                 continue;
6125                         }
6126                         if (tabular.isPartOfMultiColumn(r2, c2)) {
6127                                 --c1;
6128                                 continue;
6129                         }
6130                         shared_ptr<InsetTableCell> inset(
6131                                 new InsetTableCell(*paste_tabular->cellInset(r1, c1)));
6132                         tabular.setCellInset(r2, c2, inset);
6133                         // FIXME?: why do we need to do this explicitly? (EL)
6134                         tabular.cellInset(r2, c2)->setBuffer(tabular.buffer());
6135
6136                         // FIXME: change tracking (MG)
6137                         inset->setChange(Change(buffer().params().track_changes ?
6138                                                 Change::INSERTED : Change::UNCHANGED));
6139                         cur.pos() = 0;
6140                 }
6141         }
6142         return true;
6143 }
6144
6145
6146 void InsetTabular::cutSelection(Cursor & cur)
6147 {
6148         if (!cur.selection())
6149                 return;
6150
6151         row_type rs, re;
6152         col_type cs, ce;
6153         getSelection(cur, rs, re, cs, ce);
6154         for (row_type r = rs; r <= re; ++r) {
6155                 for (col_type c = cs; c <= ce; ++c) {
6156                         shared_ptr<InsetTableCell> t
6157                                 = cell(tabular.cellIndex(r, c));
6158                         if (buffer().params().track_changes)
6159                                 // FIXME: Change tracking (MG)
6160                                 t->setChange(Change(Change::DELETED));
6161                         else
6162                                 t->clear();
6163                 }
6164         }
6165
6166         // cursor position might be invalid now
6167         if (cur.pit() > cur.lastpit())
6168                 cur.pit() = cur.lastpit();
6169         if (cur.pos() > cur.lastpos())
6170                 cur.pos() = cur.lastpos();
6171         cur.clearSelection();
6172 }
6173
6174
6175 bool InsetTabular::isRightToLeft(Cursor & cur) const
6176 {
6177         // LASSERT: It might be better to abandon this Buffer.
6178         LASSERT(cur.depth() > 1, return false);
6179         Paragraph const & parentpar = cur[cur.depth() - 2].paragraph();
6180         pos_type const parentpos = cur[cur.depth() - 2].pos();
6181         return parentpar.getFontSettings(buffer().params(),
6182                                          parentpos).language()->rightToLeft();
6183 }
6184
6185
6186 docstring InsetTabular::asString(idx_type stidx, idx_type enidx,
6187                                  bool intoInsets)
6188 {
6189         LASSERT(stidx <= enidx, return docstring());
6190         docstring retval;
6191         col_type const col1 = tabular.cellColumn(stidx);
6192         col_type const col2 = tabular.cellColumn(enidx);
6193         row_type const row1 = tabular.cellRow(stidx);
6194         row_type const row2 = tabular.cellRow(enidx);
6195         bool first = true;
6196         for (col_type col = col1; col <= col2; col++)
6197                 for (row_type row = row1; row <= row2; row++) {
6198                         if (!first)
6199                                 retval += "\n";
6200                         else
6201                                 first = false;
6202                         retval += tabular.cellInset(row, col)->asString(intoInsets);
6203                 }
6204         return retval;
6205 }
6206
6207
6208 void InsetTabular::getSelection(Cursor & cur,
6209         row_type & rs, row_type & re, col_type & cs, col_type & ce) const
6210 {
6211         CursorSlice const & beg = cur.selBegin();
6212         CursorSlice const & end = cur.selEnd();
6213         cs = tabular.cellColumn(beg.idx());
6214         ce = tabular.cellColumn(end.idx());
6215         if (cs > ce)
6216                 swap(cs, ce);
6217
6218         rs = tabular.cellRow(beg.idx());
6219         re = tabular.cellRow(end.idx());
6220         if (rs > re)
6221                 swap(rs, re);
6222 }
6223
6224
6225 Text * InsetTabular::getText(int idx) const
6226 {
6227         return size_t(idx) < nargs() ? cell(idx)->getText(0) : 0;
6228 }
6229
6230
6231 void InsetTabular::setChange(Change const & change)
6232 {
6233         for (idx_type idx = 0; idx < nargs(); ++idx)
6234                 cell(idx)->setChange(change);
6235 }
6236
6237
6238 void InsetTabular::acceptChanges()
6239 {
6240         for (idx_type idx = 0; idx < nargs(); ++idx)
6241                 cell(idx)->acceptChanges();
6242 }
6243
6244
6245 void InsetTabular::rejectChanges()
6246 {
6247         for (idx_type idx = 0; idx < nargs(); ++idx)
6248                 cell(idx)->rejectChanges();
6249 }
6250
6251
6252 bool InsetTabular::allowParagraphCustomization(idx_type cell) const
6253 {
6254         return tabular.getPWidth(cell).zero();
6255 }
6256
6257
6258 bool InsetTabular::forcePlainLayout(idx_type cell) const
6259 {
6260         return !tabular.getPWidth(cell).zero();
6261 }
6262
6263
6264 bool InsetTabular::insertPlaintextString(BufferView & bv, docstring const & buf,
6265                                      bool usePaste)
6266 {
6267         if (buf.length() <= 0)
6268                 return true;
6269
6270         col_type cols = 1;
6271         row_type rows = 1;
6272         col_type maxCols = 1;
6273         size_t const len = buf.length();
6274         size_t p = 0;
6275
6276         while (p < len &&
6277                (p = buf.find_first_of(from_ascii("\t\n"), p)) != docstring::npos) {
6278                 switch (buf[p]) {
6279                 case '\t':
6280                         ++cols;
6281                         break;
6282                 case '\n':
6283                         if (p + 1 < len)
6284                                 ++rows;
6285                         maxCols = max(cols, maxCols);
6286                         cols = 1;
6287                         break;
6288                 }
6289                 ++p;
6290         }
6291         maxCols = max(cols, maxCols);
6292         Tabular * loctab;
6293         idx_type cell = 0;
6294         col_type ocol = 0;
6295         row_type row = 0;
6296         if (usePaste) {
6297                 paste_tabular.reset(new Tabular(buffer_, rows, maxCols));
6298                 loctab = paste_tabular.get();
6299                 dirtyTabularStack(true);
6300         } else {
6301                 loctab = &tabular;
6302                 cell = bv.cursor().idx();
6303                 ocol = tabular.cellColumn(cell);
6304                 row = tabular.cellRow(cell);
6305         }
6306
6307         size_t op = 0;
6308         idx_type const cells = loctab->numberofcells;
6309         p = 0;
6310         cols = ocol;
6311         rows = loctab->nrows();
6312         col_type const columns = loctab->ncols();
6313
6314         while (cell < cells && p < len && row < rows &&
6315                (p = buf.find_first_of(from_ascii("\t\n"), p)) != docstring::npos)
6316         {
6317                 if (p >= len)
6318                         break;
6319                 switch (buf[p]) {
6320                 case '\t':
6321                         // we can only set this if we are not too far right
6322                         if (cols < columns) {
6323                                 shared_ptr<InsetTableCell> inset = loctab->cellInset(cell);
6324                                 Font const font = bv.textMetrics(&inset->text()).
6325                                         displayFont(0, 0);
6326                                 inset->setText(buf.substr(op, p - op), font,
6327                                                buffer().params().track_changes);
6328                                 ++cols;
6329                                 ++cell;
6330                         }
6331                         break;
6332                 case '\n':
6333                         // we can only set this if we are not too far right
6334                         if (cols < columns) {
6335                                 shared_ptr<InsetTableCell> inset = tabular.cellInset(cell);
6336                                 Font const font = bv.textMetrics(&inset->text()).
6337                                         displayFont(0, 0);
6338                                 inset->setText(buf.substr(op, p - op), font,
6339                                                buffer().params().track_changes);
6340                         }
6341                         cols = ocol;
6342                         ++row;
6343                         if (row < rows)
6344                                 cell = loctab->cellIndex(row, cols);
6345                         break;
6346                 }
6347                 ++p;
6348                 op = p;
6349         }
6350         // check for the last cell if there is no trailing '\n'
6351         if (cell < cells && op < len) {
6352                 shared_ptr<InsetTableCell> inset = loctab->cellInset(cell);
6353                 Font const font = bv.textMetrics(&inset->text()).displayFont(0, 0);
6354                 inset->setText(buf.substr(op, len - op), font,
6355                         buffer().params().track_changes);
6356         }
6357         return true;
6358 }
6359
6360
6361 void InsetTabular::addPreview(DocIterator const & inset_pos,
6362         PreviewLoader & loader) const
6363 {
6364         DocIterator cell_pos = inset_pos;
6365
6366         cell_pos.push_back(CursorSlice(*const_cast<InsetTabular *>(this)));
6367         for (row_type r = 0; r < tabular.nrows(); ++r) {
6368                 for (col_type c = 0; c < tabular.ncols(); ++c) {
6369                         cell_pos.top().idx() = tabular.cellIndex(r, c);
6370                         tabular.cellInset(r, c)->addPreview(cell_pos, loader);
6371                 }
6372         }
6373 }
6374
6375
6376 bool InsetTabular::completionSupported(Cursor const & cur) const
6377 {
6378         Cursor const & bvCur = cur.bv().cursor();
6379         if (&bvCur.inset() != this)
6380                 return false;
6381         return cur.text()->completionSupported(cur);
6382 }
6383
6384
6385 bool InsetTabular::inlineCompletionSupported(Cursor const & cur) const
6386 {
6387         return completionSupported(cur);
6388 }
6389
6390
6391 bool InsetTabular::automaticInlineCompletion() const
6392 {
6393         return lyxrc.completion_inline_text;
6394 }
6395
6396
6397 bool InsetTabular::automaticPopupCompletion() const
6398 {
6399         return lyxrc.completion_popup_text;
6400 }
6401
6402
6403 bool InsetTabular::showCompletionCursor() const
6404 {
6405         return lyxrc.completion_cursor_text;
6406 }
6407
6408
6409 CompletionList const * InsetTabular::createCompletionList(Cursor const & cur) const
6410 {
6411         return completionSupported(cur) ? cur.text()->createCompletionList(cur) : 0;
6412 }
6413
6414
6415 docstring InsetTabular::completionPrefix(Cursor const & cur) const
6416 {
6417         if (!completionSupported(cur))
6418                 return docstring();
6419         return cur.text()->completionPrefix(cur);
6420 }
6421
6422
6423 bool InsetTabular::insertCompletion(Cursor & cur, docstring const & s, bool finished)
6424 {
6425         if (!completionSupported(cur))
6426                 return false;
6427
6428         return cur.text()->insertCompletion(cur, s, finished);
6429 }
6430
6431
6432 void InsetTabular::completionPosAndDim(Cursor const & cur, int & x, int & y,
6433                                     Dimension & dim) const
6434 {
6435         TextMetrics const & tm = cur.bv().textMetrics(cur.text());
6436         tm.completionPosAndDim(cur, x, y, dim);
6437 }
6438
6439
6440 void InsetTabular::string2params(string const & in, InsetTabular & inset)
6441 {
6442         istringstream data(in);
6443         Lexer lex;
6444         lex.setStream(data);
6445
6446         if (in.empty())
6447                 return;
6448
6449         string token;
6450         lex >> token;
6451         if (!lex || token != "tabular") {
6452                 LYXERR0("Expected arg 1 to be \"tabular\" in " << in);
6453                 return;
6454         }
6455
6456         // This is part of the inset proper that is usually swallowed
6457         // by Buffer::readInset
6458         lex >> token;
6459         if (!lex || token != "Tabular") {
6460                 LYXERR0("Expected arg 2 to be \"Tabular\" in " << in);
6461                 return;
6462         }
6463
6464         inset.read(lex);
6465 }
6466
6467
6468 string InsetTabular::params2string(InsetTabular const & inset)
6469 {
6470         ostringstream data;
6471         data << "tabular" << ' ';
6472         inset.write(data);
6473         data << "\\end_inset\n";
6474         return data.str();
6475 }
6476
6477
6478 void InsetTabular::setLayoutForHiddenCells(DocumentClass const & dc)
6479 {
6480         for (Tabular::col_type c = 0; c < tabular.ncols(); ++c) {
6481                 for (Tabular::row_type r = 0; r < tabular.nrows(); ++r) {
6482                         if (!tabular.isPartOfMultiColumn(r,c) &&
6483                             !tabular.isPartOfMultiRow(r,c))
6484                                 continue;
6485
6486                         ParagraphList & parlist = tabular.cellInset(r,c)->paragraphs();
6487                         ParagraphList::iterator it = parlist.begin();
6488                         ParagraphList::iterator const en = parlist.end();
6489                         for (; it != en; ++it)
6490                                         it->setLayout(dc.plainLayout());
6491                 }
6492         }
6493 }
6494
6495
6496 } // namespace lyx