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