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