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