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