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