]> git.lyx.org Git - lyx.git/blob - src/insets/InsetTabular.cpp
- unset multicol (row) when setting multirow (col)
[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 Tabular::col_type Tabular::cellRightColumn(idx_type cell) const
1306 {
1307         row_type const row = cellRow(cell);
1308         col_type column = cellColumn(cell);
1309         while (column < column_info.size() - 1 &&
1310                    cell_info[row][column + 1].multicolumn == CELL_PART_OF_MULTICOLUMN)
1311                 ++column;
1312         return column;
1313 }
1314
1315
1316 void Tabular::write(ostream & os) const
1317 {
1318         // header line
1319         os << "<lyxtabular"
1320            << write_attribute("version", 3)
1321            << write_attribute("rows", row_info.size())
1322            << write_attribute("columns", column_info.size())
1323            << ">\n";
1324         // global longtable options
1325         os << "<features"
1326            << write_attribute("rotate", rotate)
1327            << write_attribute("booktabs", use_booktabs)
1328            << write_attribute("islongtable", is_long_tabular)
1329            << write_attribute("firstHeadTopDL", endfirsthead.topDL)
1330            << write_attribute("firstHeadBottomDL", endfirsthead.bottomDL)
1331            << write_attribute("firstHeadEmpty", endfirsthead.empty)
1332            << write_attribute("headTopDL", endhead.topDL)
1333            << write_attribute("headBottomDL", endhead.bottomDL)
1334            << write_attribute("footTopDL", endfoot.topDL)
1335            << write_attribute("footBottomDL", endfoot.bottomDL)
1336            << write_attribute("lastFootTopDL", endlastfoot.topDL)
1337            << write_attribute("lastFootBottomDL", endlastfoot.bottomDL)
1338            << write_attribute("lastFootEmpty", endlastfoot.empty);
1339         // longtables cannot be aligned vertically
1340         if (!is_long_tabular)
1341            os << write_attribute("tabularvalignment", tabular_valignment);
1342         if (is_long_tabular)
1343            os << write_attribute("longtabularalignment",
1344                                  longtabular_alignment);
1345         os << ">\n";
1346         for (col_type j = 0; j < column_info.size(); ++j) {
1347                 os << "<column"
1348                    << write_attribute("alignment", column_info[j].alignment)
1349                    << write_attribute("valignment", column_info[j].valignment)
1350                    << write_attribute("width", column_info[j].p_width.asString())
1351                    << write_attribute("special", column_info[j].align_special)
1352                    << ">\n";
1353         }
1354         for (row_type i = 0; i < row_info.size(); ++i) {
1355                 static const string def("default");
1356                 os << "<row";
1357                 if (row_info[i].top_space_default)
1358                         os << write_attribute("topspace", def);
1359                 else
1360                         os << write_attribute("topspace", row_info[i].top_space);
1361                 if (row_info[i].bottom_space_default)
1362                         os << write_attribute("bottomspace", def);
1363                 else
1364                         os << write_attribute("bottomspace", row_info[i].bottom_space);
1365                 if (row_info[i].interline_space_default)
1366                         os << write_attribute("interlinespace", def);
1367                 else
1368                         os << write_attribute("interlinespace", row_info[i].interline_space);
1369                 os << write_attribute("endhead", row_info[i].endhead)
1370                    << write_attribute("endfirsthead", row_info[i].endfirsthead)
1371                    << write_attribute("endfoot", row_info[i].endfoot)
1372                    << write_attribute("endlastfoot", row_info[i].endlastfoot)
1373                    << write_attribute("newpage", row_info[i].newpage)
1374                    << write_attribute("caption", row_info[i].caption)
1375                    << ">\n";
1376                 for (col_type j = 0; j < column_info.size(); ++j) {
1377                         os << "<cell"
1378                            << write_attribute("multicolumn", cell_info[i][j].multicolumn)
1379                            << write_attribute("multirow", cell_info[i][j].multirow)
1380                            << write_attribute("alignment", cell_info[i][j].alignment)
1381                            << write_attribute("valignment", cell_info[i][j].valignment)
1382                            << write_attribute("topline", cell_info[i][j].top_line)
1383                            << write_attribute("bottomline", cell_info[i][j].bottom_line)
1384                            << write_attribute("leftline", cell_info[i][j].left_line)
1385                            << write_attribute("rightline", cell_info[i][j].right_line)
1386                            << write_attribute("rotate", cell_info[i][j].rotate)
1387                            << write_attribute("usebox", cell_info[i][j].usebox)
1388                            << write_attribute("width", cell_info[i][j].p_width)
1389                            << write_attribute("special", cell_info[i][j].align_special)
1390                            << ">\n";
1391                         os << "\\begin_inset ";
1392                         cell_info[i][j].inset->write(os);
1393                         os << "\n\\end_inset\n"
1394                            << "</cell>\n";
1395                 }
1396                 os << "</row>\n";
1397         }
1398         os << "</lyxtabular>\n";
1399 }
1400
1401
1402 void Tabular::read(Lexer & lex)
1403 {
1404         string line;
1405         istream & is = lex.getStream();
1406
1407         l_getline(is, line);
1408         if (!prefixIs(line, "<lyxtabular ") && !prefixIs(line, "<Tabular ")) {
1409                 LASSERT(false, /**/);
1410                 return;
1411         }
1412
1413         int version;
1414         if (!getTokenValue(line, "version", version))
1415                 return;
1416         LASSERT(version >= 2, /**/);
1417
1418         int rows_arg;
1419         if (!getTokenValue(line, "rows", rows_arg))
1420                 return;
1421         int columns_arg;
1422         if (!getTokenValue(line, "columns", columns_arg))
1423                 return;
1424         init(buffer_, rows_arg, columns_arg);
1425         l_getline(is, line);
1426         if (!prefixIs(line, "<features")) {
1427                 lyxerr << "Wrong tabular format (expected <features ...> got"
1428                        << line << ')' << endl;
1429                 return;
1430         }
1431         getTokenValue(line, "rotate", rotate);
1432         getTokenValue(line, "booktabs", use_booktabs);
1433         getTokenValue(line, "islongtable", is_long_tabular);
1434         getTokenValue(line, "tabularvalignment", tabular_valignment);
1435         getTokenValue(line, "longtabularalignment", longtabular_alignment);
1436         getTokenValue(line, "firstHeadTopDL", endfirsthead.topDL);
1437         getTokenValue(line, "firstHeadBottomDL", endfirsthead.bottomDL);
1438         getTokenValue(line, "firstHeadEmpty", endfirsthead.empty);
1439         getTokenValue(line, "headTopDL", endhead.topDL);
1440         getTokenValue(line, "headBottomDL", endhead.bottomDL);
1441         getTokenValue(line, "footTopDL", endfoot.topDL);
1442         getTokenValue(line, "footBottomDL", endfoot.bottomDL);
1443         getTokenValue(line, "lastFootTopDL", endlastfoot.topDL);
1444         getTokenValue(line, "lastFootBottomDL", endlastfoot.bottomDL);
1445         getTokenValue(line, "lastFootEmpty", endlastfoot.empty);
1446
1447         for (col_type j = 0; j < column_info.size(); ++j) {
1448                 l_getline(is,line);
1449                 if (!prefixIs(line,"<column")) {
1450                         lyxerr << "Wrong tabular format (expected <column ...> got"
1451                                << line << ')' << endl;
1452                         return;
1453                 }
1454                 getTokenValue(line, "alignment", column_info[j].alignment);
1455                 getTokenValue(line, "valignment", column_info[j].valignment);
1456                 getTokenValue(line, "width", column_info[j].p_width);
1457                 getTokenValue(line, "special", column_info[j].align_special);
1458         }
1459
1460         for (row_type i = 0; i < row_info.size(); ++i) {
1461                 l_getline(is, line);
1462                 if (!prefixIs(line, "<row")) {
1463                         lyxerr << "Wrong tabular format (expected <row ...> got"
1464                                << line << ')' << endl;
1465                         return;
1466                 }
1467                 getTokenValue(line, "topspace", row_info[i].top_space,
1468                               row_info[i].top_space_default);
1469                 getTokenValue(line, "bottomspace", row_info[i].bottom_space,
1470                               row_info[i].bottom_space_default);
1471                 getTokenValue(line, "interlinespace", row_info[i].interline_space,
1472                               row_info[i].interline_space_default);
1473                 getTokenValue(line, "endfirsthead", row_info[i].endfirsthead);
1474                 getTokenValue(line, "endhead", row_info[i].endhead);
1475                 getTokenValue(line, "endfoot", row_info[i].endfoot);
1476                 getTokenValue(line, "endlastfoot", row_info[i].endlastfoot);
1477                 getTokenValue(line, "newpage", row_info[i].newpage);
1478                 getTokenValue(line, "caption", row_info[i].caption);
1479                 for (col_type j = 0; j < column_info.size(); ++j) {
1480                         l_getline(is, line);
1481                         if (!prefixIs(line, "<cell")) {
1482                                 lyxerr << "Wrong tabular format (expected <cell ...> got"
1483                                        << line << ')' << endl;
1484                                 return;
1485                         }
1486                         getTokenValue(line, "multicolumn", cell_info[i][j].multicolumn);
1487                         getTokenValue(line, "multirow", cell_info[i][j].multirow);
1488                         getTokenValue(line, "alignment", cell_info[i][j].alignment);
1489                         getTokenValue(line, "valignment", cell_info[i][j].valignment);
1490                         getTokenValue(line, "topline", cell_info[i][j].top_line);
1491                         getTokenValue(line, "bottomline", cell_info[i][j].bottom_line);
1492                         getTokenValue(line, "leftline", cell_info[i][j].left_line);
1493                         getTokenValue(line, "rightline", cell_info[i][j].right_line);
1494                         getTokenValue(line, "rotate", cell_info[i][j].rotate);
1495                         getTokenValue(line, "usebox", cell_info[i][j].usebox);
1496                         getTokenValue(line, "width", cell_info[i][j].p_width);
1497                         setFixedWidth(i,j);
1498                         getTokenValue(line, "special", cell_info[i][j].align_special);
1499                         l_getline(is, line);
1500                         if (prefixIs(line, "\\begin_inset")) {
1501                                 cell_info[i][j].inset->setBuffer(*buffer_);
1502                                 cell_info[i][j].inset->read(lex);
1503                                 l_getline(is, line);
1504                         }
1505                         if (!prefixIs(line, "</cell>")) {
1506                                 lyxerr << "Wrong tabular format (expected </cell> got"
1507                                        << line << ')' << endl;
1508                                 return;
1509                         }
1510                 }
1511                 l_getline(is, line);
1512                 if (!prefixIs(line, "</row>")) {
1513                         lyxerr << "Wrong tabular format (expected </row> got"
1514                                << line << ')' << endl;
1515                         return;
1516                 }
1517         }
1518         while (!prefixIs(line, "</lyxtabular>")) {
1519                 l_getline(is, line);
1520         }
1521         updateIndexes();
1522 }
1523
1524
1525 bool Tabular::isMultiColumn(idx_type cell) const
1526 {
1527         return (cellInfo(cell).multicolumn == CELL_BEGIN_OF_MULTICOLUMN 
1528                 || cellInfo(cell).multicolumn == CELL_PART_OF_MULTICOLUMN);
1529 }
1530
1531
1532 bool Tabular::isMultiColumnReal(idx_type cell) const
1533 {
1534         return cellColumn(cell) != cellRightColumn(cell) && isMultiColumn(cell);
1535 }
1536
1537
1538 Tabular::CellData & Tabular::cellInfo(idx_type cell) const
1539 {
1540         return cell_info[cellRow(cell)][cellColumn(cell)];
1541 }
1542
1543
1544 void Tabular::setMultiColumn(idx_type cell, idx_type number)
1545 {
1546         idx_type const col = cellColumn(cell);
1547         idx_type const row = cellRow(cell);
1548         for (idx_type i = 0; i < number; ++i)
1549                 unsetMultiRow(cellIndex(row, col + i));
1550
1551         CellData & cs = cellInfo(cell);
1552         cs.multicolumn = CELL_BEGIN_OF_MULTICOLUMN;
1553         cs.alignment = column_info[cellColumn(cell)].alignment;
1554         setRightLine(cell, rightLine(cell + number - 1));
1555
1556         for (idx_type i = 1; i < number; ++i) {
1557                 CellData & cs1 = cellInfo(cell + i);
1558                 cs1.multicolumn = CELL_PART_OF_MULTICOLUMN;
1559                 cs.inset->appendParagraphs(cs1.inset->paragraphs());
1560                 cs1.inset->clear();
1561         }
1562         updateIndexes();
1563 }
1564
1565
1566 bool Tabular::isMultiRow(idx_type cell) const
1567 {
1568         return (cellInfo(cell).multirow == CELL_BEGIN_OF_MULTIROW
1569                 || cellInfo(cell).multirow == CELL_PART_OF_MULTIROW);
1570 }
1571
1572
1573 void Tabular::setMultiRow(idx_type cell, idx_type number)
1574 {
1575         idx_type const col = cellColumn(cell);
1576         idx_type const row = cellRow(cell);
1577         for (idx_type i = 0; i < number; ++i)
1578                 unsetMultiColumn(cellIndex(row + i, col));
1579
1580         idx_type const ncols = column_info.size();
1581         CellData & cs = cellInfo(cell);
1582         cs.multirow = CELL_BEGIN_OF_MULTIROW;
1583         // FIXME: the horizontal alignment can only be changed for
1584         // the whole table, support for this needs to be implemented
1585         // assigning this to uwestoehr
1586         cs.valignment = LYX_VALIGN_MIDDLE;
1587         // set the bottom row of the last selected cell
1588         setBottomLine(cell, bottomLine(cell + (number - 1)*ncols));
1589
1590         for (idx_type i = 1; i < number; ++i) {
1591                 CellData & cs1 = cell_info[row + i][col];
1592                 cs1.multirow = CELL_PART_OF_MULTIROW;
1593                 cs.inset->appendParagraphs(cs1.inset->paragraphs());
1594                 cs1.inset->clear();
1595         }
1596         updateIndexes();
1597 }
1598
1599
1600 Tabular::idx_type Tabular::columnSpan(idx_type cell) const
1601 {
1602         row_type const row = cellRow(cell);
1603         col_type const ncols = column_info.size();
1604         col_type column = cellColumn(cell) + 1;
1605         while (column < ncols && isPartOfMultiColumn(row, column))
1606                 ++column;
1607
1608         return column - cellColumn(cell);
1609 }
1610
1611
1612 Tabular::idx_type Tabular::rowSpan(idx_type cell) const
1613 {
1614         row_type const nrows = row_info.size();
1615         col_type const column = cellColumn(cell);
1616         col_type row = cellRow(cell) + 1;
1617         while (row < nrows && isPartOfMultiRow(row, column))
1618                 ++row;
1619         
1620         return row - cellRow(cell);
1621 }
1622
1623
1624 void Tabular::unsetMultiColumn(idx_type cell)
1625 {
1626         if (!isMultiColumn(cell))
1627                 return;
1628
1629         row_type const row = cellRow(cell);
1630         col_type const col = cellColumn(cell);
1631         row_type const span = columnSpan(cell);
1632         for (col_type c = 0; c < span; ++c)
1633                 cell_info[row][col + c].multicolumn = CELL_NORMAL;
1634         updateIndexes();
1635 }
1636
1637
1638 void Tabular::unsetMultiRow(idx_type cell)
1639 {
1640         if (!isMultiRow(cell))
1641                 return;
1642
1643         row_type const row = cellRow(cell);
1644         col_type const col = cellColumn(cell);
1645         row_type const span = rowSpan(cell);
1646         for (row_type r = 0; r < span; ++r)
1647                 cell_info[row + r][col].multirow = CELL_NORMAL;
1648         updateIndexes();
1649 }
1650
1651
1652 void Tabular::setRotateCell(idx_type cell, bool flag)
1653 {
1654         cellInfo(cell).rotate = flag;
1655 }
1656
1657
1658 bool Tabular::getRotateCell(idx_type cell) const
1659 {
1660         return cellInfo(cell).rotate;
1661 }
1662
1663
1664 bool Tabular::needRotating() const
1665 {
1666         if (rotate)
1667                 return true;
1668         for (row_type i = 0; i < row_info.size(); ++i)
1669                 for (col_type j = 0; j < column_info.size(); ++j)
1670                         if (cell_info[i][j].rotate)
1671                                 return true;
1672         return false;
1673 }
1674
1675
1676 bool Tabular::isLastCell(idx_type cell) const
1677 {
1678         if (cell + 1 < numberofcells)
1679                 return false;
1680         return true;
1681 }
1682
1683
1684 Tabular::idx_type Tabular::cellAbove(idx_type cell) const
1685 {
1686         if (cellRow(cell) == 0)
1687                 return cell;
1688         
1689         col_type const col = cellColumn(cell);
1690         row_type r = cellRow(cell) - 1;
1691         while (r > 0 && cell_info[r][col].multirow == CELL_PART_OF_MULTIROW)
1692                 --r;
1693
1694         return cell_info[r][col].cellno;
1695 }
1696
1697
1698 Tabular::idx_type Tabular::cellBelow(idx_type cell) const
1699 {
1700         row_type const nextrow = cellRow(cell) + rowSpan(cell);
1701         if (nextrow < row_info.size())
1702                 return cell_info[nextrow][cellColumn(cell)].cellno;
1703         return cell;
1704 }
1705
1706
1707 Tabular::idx_type Tabular::cellIndex(row_type row, col_type column) const
1708 {
1709         LASSERT(column != npos && column < column_info.size()
1710                 && row != npos && row < row_info.size(), /**/);
1711         return cell_info[row][column].cellno;
1712 }
1713
1714
1715 void Tabular::setUsebox(idx_type cell, BoxType type)
1716 {
1717         cellInfo(cell).usebox = type;
1718 }
1719
1720
1721 // FIXME: Remove this routine because we cannot insert \parboxes when the user
1722 // adds line breaks, see bug 4886.
1723 Tabular::BoxType Tabular::getUsebox(idx_type cell) const
1724 {
1725         if ((!column_info[cellColumn(cell)].p_width.zero() && !isMultiColumn(cell)) ||
1726                 (isMultiColumn(cell) && !cellInfo(cell).p_width.zero()))
1727                 return BOX_NONE;
1728         if (cellInfo(cell).usebox > 1)
1729                 return cellInfo(cell).usebox;
1730         return useParbox(cell);
1731 }
1732
1733
1734 ///
1735 //  This are functions used for the longtable support
1736 ///
1737 void Tabular::setLTHead(row_type row, bool flag, ltType const & hd,
1738                            bool first)
1739 {
1740         if (first) {
1741                 endfirsthead = hd;
1742                 if (hd.set)
1743                         row_info[row].endfirsthead = flag;
1744         } else {
1745                 endhead = hd;
1746                 if (hd.set)
1747                         row_info[row].endhead = flag;
1748         }
1749 }
1750
1751
1752 bool Tabular::getRowOfLTHead(row_type row, ltType & hd) const
1753 {
1754         hd = endhead;
1755         hd.set = haveLTHead();
1756         return row_info[row].endhead;
1757 }
1758
1759
1760 bool Tabular::getRowOfLTFirstHead(row_type row, ltType & hd) const
1761 {
1762         hd = endfirsthead;
1763         hd.set = haveLTFirstHead();
1764         return row_info[row].endfirsthead;
1765 }
1766
1767
1768 void Tabular::setLTFoot(row_type row, bool flag, ltType const & fd,
1769                            bool last)
1770 {
1771         if (last) {
1772                 endlastfoot = fd;
1773                 if (fd.set)
1774                         row_info[row].endlastfoot = flag;
1775         } else {
1776                 endfoot = fd;
1777                 if (fd.set)
1778                         row_info[row].endfoot = flag;
1779         }
1780 }
1781
1782
1783 bool Tabular::getRowOfLTFoot(row_type row, ltType & fd) const
1784 {
1785         fd = endfoot;
1786         fd.set = haveLTFoot();
1787         return row_info[row].endfoot;
1788 }
1789
1790
1791 bool Tabular::getRowOfLTLastFoot(row_type row, ltType & fd) const
1792 {
1793         fd = endlastfoot;
1794         fd.set = haveLTLastFoot();
1795         return row_info[row].endlastfoot;
1796 }
1797
1798
1799 void Tabular::setLTNewPage(row_type row, bool what)
1800 {
1801         row_info[row].newpage = what;
1802 }
1803
1804
1805 bool Tabular::getLTNewPage(row_type row) const
1806 {
1807         return row_info[row].newpage;
1808 }
1809
1810
1811 bool Tabular::haveLTHead() const
1812 {
1813         for (row_type i = 0; i < row_info.size(); ++i)
1814                 if (row_info[i].endhead)
1815                         return true;
1816         return false;
1817 }
1818
1819
1820 bool Tabular::haveLTFirstHead() const
1821 {
1822         if (endfirsthead.empty)
1823                 return false;
1824         for (row_type i = 0; i < row_info.size(); ++i)
1825                 if (row_info[i].endfirsthead)
1826                         return true;
1827         return false;
1828 }
1829
1830
1831 bool Tabular::haveLTFoot() const
1832 {
1833         for (row_type i = 0; i < row_info.size(); ++i)
1834                 if (row_info[i].endfoot)
1835                         return true;
1836         return false;
1837 }
1838
1839
1840 bool Tabular::haveLTLastFoot() const
1841 {
1842         if (endlastfoot.empty)
1843                 return false;
1844         for (row_type i = 0; i < row_info.size(); ++i)
1845                 if (row_info[i].endlastfoot)
1846                         return true;
1847         return false;
1848 }
1849
1850
1851 Tabular::idx_type Tabular::setLTCaption(row_type row, bool what)
1852 {
1853         idx_type i = getFirstCellInRow(row);
1854         if (what) {
1855                 setMultiColumn(i, numberOfCellsInRow(row));
1856                 setTopLine(i, false);
1857                 setBottomLine(i, false);
1858                 setLeftLine(i, false);
1859                 setRightLine(i, false);
1860         } else {
1861                 unsetMultiColumn(i);
1862                 // When unsetting a caption row, also all existing
1863                 // captions in this row must be dissolved.
1864         }
1865         row_info[row].caption = what;
1866         return i;
1867 }
1868
1869
1870 bool Tabular::ltCaption(row_type row) const
1871 {
1872         return row_info[row].caption;
1873 }
1874
1875
1876 bool Tabular::haveLTCaption() const
1877 {
1878         for (row_type i = 0; i < row_info.size(); ++i)
1879                 if (row_info[i].caption)
1880                         return true;
1881         return false;
1882 }
1883
1884
1885 // end longtable support functions
1886
1887 void Tabular::setRowAscent(row_type row, int height)
1888 {
1889         if (row >= row_info.size() || row_info[row].ascent == height)
1890                 return;
1891         row_info[row].ascent = height;
1892 }
1893
1894
1895 void Tabular::setRowDescent(row_type row, int height)
1896 {
1897         if (row >= row_info.size() || row_info[row].descent == height)
1898                 return;
1899         row_info[row].descent = height;
1900 }
1901
1902
1903 int Tabular::rowAscent(row_type row) const
1904 {
1905         LASSERT(row < row_info.size(), /**/);
1906         return row_info[row].ascent;
1907 }
1908
1909
1910 int Tabular::rowDescent(row_type row) const
1911 {
1912         LASSERT(row < row_info.size(), /**/);
1913         return row_info[row].descent;
1914 }
1915
1916
1917 int Tabular::height() const
1918 {
1919         int height = 0;
1920         for (row_type row = 0; row < row_info.size(); ++row)
1921                 height += rowAscent(row) + rowDescent(row) +
1922                         interRowSpace(row);
1923         return height;
1924 }
1925
1926
1927 bool Tabular::isPartOfMultiColumn(row_type row, col_type column) const
1928 {
1929         LASSERT(row < row_info.size(), /**/);
1930         LASSERT(column < column_info.size(), /**/);
1931         return cell_info[row][column].multicolumn == CELL_PART_OF_MULTICOLUMN;
1932 }
1933
1934
1935 bool Tabular::isPartOfMultiRow(row_type row, col_type column) const
1936 {
1937         LASSERT(row < row_info.size(), /**/);
1938         LASSERT(column < column_info.size(), /**/);
1939         return cell_info[row][column].multirow == CELL_PART_OF_MULTIROW;
1940 }
1941
1942
1943 int Tabular::TeXTopHLine(odocstream & os, row_type row, string const lang) const
1944 {
1945         // we only output complete row lines and the 1st row here, the rest
1946         // is done in Tabular::TeXBottomHLine(...)
1947
1948         // get for each column the topline (if any)
1949         col_type const ncols = column_info.size();
1950         vector<bool> topline;
1951         col_type nset = 0;
1952         for (col_type c = 0; c < ncols; ++c) {
1953                 topline.push_back(topLine(cellIndex(row, c)));
1954                 // If cell is part of a multirow and not the first cell of the
1955                 // multirow, no line must be drawn.
1956                 if (row != 0)
1957                         if (isMultiRow(cellIndex(row, c))
1958                                 && isMultiRow(cellIndex(row - 1, c)))
1959                                         topline[c] = false;
1960                 if (topline[c])
1961                         ++nset;
1962         }
1963
1964         // do nothing if empty first row, or incomplete row line after
1965         if ((row == 0 && nset == 0) || (row > 0 && nset != ncols))
1966                 return 0;
1967
1968         // only output complete row lines and the 1st row's clines
1969         if (nset == ncols) {
1970                 if (use_booktabs) {
1971                         os << (row == 0 ? "\\toprule " : "\\midrule ");
1972                 } else {
1973                         os << "\\hline ";
1974                 }
1975         } else if (row == 0) {
1976                 for (col_type c = 0; c < ncols; ++c) {
1977                         if (topline[c]) {
1978                                 //babel makes the "-" character an active one, so we have to suppress this here
1979                                 //see http://groups.google.com/group/comp.text.tex/browse_thread/thread/af769424a4a0f289#
1980                                 if (lang == "slovak" || lang == "czech")
1981                                         os << (use_booktabs ? "\\expandafter\\cmidrule\\expandafter{\\expandafter" :
1982                                                               "\\expandafter\\cline\\expandafter{\\expandafter")
1983                                                                                   << c + 1 << "\\string-";
1984                                 else
1985                                         os << (use_booktabs ? "\\cmidrule{" : "\\cline{") << c + 1 << '-';
1986                                 // get to last column of line span
1987                                 while (c < ncols && topline[c])
1988                                         ++c;
1989                                 os << c << "} ";
1990                         }
1991                 }
1992         }
1993         os << "\n";
1994         return 1;
1995 }
1996
1997
1998 int Tabular::TeXBottomHLine(odocstream & os, row_type row, string const lang) const
1999 {
2000         // we output bottomlines of row r and the toplines of row r+1
2001         // if the latter do not span the whole tabular
2002
2003         // get the bottomlines of row r, and toplines in next row
2004         bool lastrow = row == row_info.size() - 1;
2005         col_type const ncols = column_info.size();
2006         vector<bool> bottomline, topline;
2007         bool nextrowset = true;
2008         for (col_type c = 0; c < ncols; ++c) {
2009                 bottomline.push_back(bottomLine(cellIndex(row, c)));
2010                 topline.push_back(!lastrow && topLine(cellIndex(row + 1, c)));
2011                 // If cell is part of a multirow and not the last or first cell of the
2012                 // multirow, no line must be drawn.
2013                 if (!lastrow)
2014                         if (isMultiRow(cellIndex(row, c))
2015                                 && isMultiRow(cellIndex(row + 1, c))) {
2016                                         bottomline[c] = false;
2017                                         topline[c] = false;
2018                                 }
2019                 nextrowset &= topline[c];
2020         }
2021
2022         // combine this row's bottom lines and next row's toplines if necessary
2023         col_type nset = 0;
2024         for (col_type c = 0; c < ncols; ++c) {
2025                 if (!nextrowset)
2026                         bottomline[c] = bottomline[c] || topline[c];
2027                 if (bottomline[c])
2028                         ++nset;
2029         }
2030
2031         // do nothing if empty, OR incomplete row line with a topline in next row
2032         if (nset == 0 || (nextrowset && nset != ncols))
2033                 return 0;
2034
2035         if (nset == ncols) {
2036                 if (use_booktabs)
2037                         os << (lastrow ? "\\bottomrule" : "\\midrule");
2038                 else
2039                         os << "\\hline ";
2040         } else {
2041                 for (col_type c = 0; c < ncols; ++c) {
2042                         if (bottomline[c]) {
2043                                 //babel makes the "-" character an active one, so we have to suppress this here
2044                                 //see http://groups.google.com/group/comp.text.tex/browse_thread/thread/af769424a4a0f289#
2045                                 if (lang == "slovak" || lang == "czech")
2046                                         os << (use_booktabs ? "\\expandafter\\cmidrule\\expandafter{\\expandafter" :
2047                                                               "\\expandafter\\cline\\expandafter{\\expandafter")
2048                                                                                   << c + 1 << "\\string-";
2049                                 else
2050                                         os << (use_booktabs ? "\\cmidrule{" : "\\cline{") << c + 1 << '-';
2051                                 // get to last column of line span
2052                                 while (c < ncols && bottomline[c])
2053                                         ++c;
2054                                 os << c << "} ";
2055                         }
2056                 }
2057         }
2058         os << "\n";
2059         return 1;
2060 }
2061
2062
2063 int Tabular::TeXCellPreamble(odocstream & os, idx_type cell,
2064                                                          bool & ismulticol, bool & ismultirow) const
2065 {
2066         int ret = 0;
2067         row_type const r = cellRow(cell);
2068         if (is_long_tabular && row_info[r].caption)
2069                 return ret;
2070
2071         Tabular::VAlignment valign =  getVAlignment(cell, !isMultiColumn(cell));
2072         LyXAlignment align = getAlignment(cell, !isMultiColumn(cell));
2073         // figure out how to set the lines
2074         // we always set double lines to the right of the cell
2075         col_type const c = cellColumn(cell);
2076         col_type const nextcol = c + columnSpan(cell);
2077         bool colright = columnRightLine(c);
2078         bool colleft = columnLeftLine(c);
2079         bool nextcolleft = nextcol < column_info.size() && columnLeftLine(nextcol);
2080         bool nextcellleft = nextcol < column_info.size() 
2081                 && leftLine(cellIndex(r, nextcol));
2082         bool coldouble = colright && nextcolleft;
2083         bool celldouble = rightLine(cell) && nextcellleft;
2084
2085         ismulticol = isMultiColumn(cell)
2086                 || (c == 0 && colleft != leftLine(cell))
2087                 || ((colright || nextcolleft) && !rightLine(cell) && !nextcellleft)
2088                 || (!colright && !nextcolleft && (rightLine(cell) || nextcellleft))
2089                 || (coldouble != celldouble);
2090         if (ismulticol) {
2091                 os << "\\multicolumn{" << columnSpan(cell) << "}{";
2092                 if (c ==0 && leftLine(cell))
2093                         os << '|';
2094                 if (!cellInfo(cell).align_special.empty()) {
2095                         os << cellInfo(cell).align_special;
2096                 } else {
2097                         if (!getPWidth(cell).zero()) {
2098                                 switch (align) {
2099                                 case LYX_ALIGN_LEFT:
2100                                         os << ">{\\raggedright}";
2101                                         break;
2102                                 case LYX_ALIGN_RIGHT:
2103                                         os << ">{\\raggedleft}";
2104                                         break;
2105                                 case LYX_ALIGN_CENTER:
2106                                         os << ">{\\centering}";
2107                                         break;
2108                                 default:
2109                                         break;
2110                                 }
2111                                 switch (valign) {
2112                                 case LYX_VALIGN_TOP:
2113                                         os << 'p';
2114                                         break;
2115                                 case LYX_VALIGN_MIDDLE:
2116                                         os << 'm';
2117                                         break;
2118                                 case LYX_VALIGN_BOTTOM:
2119                                         os << 'b';
2120                                         break;
2121                                 }
2122                                 os << '{'
2123                                    << from_ascii(getPWidth(cell).asLatexString())
2124                                    << '}';
2125                         } else {
2126                                 switch (align) {
2127                                 case LYX_ALIGN_LEFT:
2128                                         os << 'l';
2129                                         break;
2130                                 case LYX_ALIGN_RIGHT:
2131                                         os << 'r';
2132                                         break;
2133                                 default:
2134                                         os << 'c';
2135                                         break;
2136                                 }
2137                         } // end if else !getPWidth
2138                 } // end if else !cellinfo_of_cell
2139                 if (rightLine(cell) || nextcellleft)
2140                         os << '|';
2141                 if (celldouble)
2142                         // add extra vertical line if we want a double one
2143                         os << '|';
2144                 os << "}{";
2145                 } // end if ismulticol
2146
2147         // we only need code for the first multirow cell
2148         ismultirow = isMultiRow(cell);
2149         if (ismultirow) {
2150                 os << "\\multirow{" << rowSpan(cell) << "}{";
2151                 if (!getPWidth(cell).zero())
2152                         os << from_ascii(getPWidth(cell).asLatexString());
2153                 else
2154                         // we need to set a default value
2155                         // needs to be discussed
2156                         os << "2.0cm";
2157                 os << "}{";
2158                 } // end if ismultirow
2159
2160         if (getRotateCell(cell)) {
2161                 os << "\\begin{sideways}\n";
2162                 ++ret;
2163         }
2164         if (getUsebox(cell) == BOX_PARBOX) {
2165                 os << "\\parbox[";
2166                 switch (valign) {
2167                 case LYX_VALIGN_TOP:
2168                         os << 't';
2169                         break;
2170                 case LYX_VALIGN_MIDDLE:
2171                         os << 'c';
2172                         break;
2173                 case LYX_VALIGN_BOTTOM:
2174                         os << 'b';
2175                         break;
2176                 }
2177                 os << "]{" << from_ascii(getPWidth(cell).asLatexString())
2178                    << "}{";
2179         } else if (getUsebox(cell) == BOX_MINIPAGE) {
2180                 os << "\\begin{minipage}[";
2181                 switch (valign) {
2182                 case LYX_VALIGN_TOP:
2183                         os << 't';
2184                         break;
2185                 case LYX_VALIGN_MIDDLE:
2186                         os << 'm';
2187                         break;
2188                 case LYX_VALIGN_BOTTOM:
2189                         os << 'b';
2190                         break;
2191                 }
2192                 os << "]{" << from_ascii(getPWidth(cell).asLatexString())
2193                    << "}\n";
2194                 ++ret;
2195         }
2196         return ret;
2197 }
2198
2199
2200 int Tabular::TeXCellPostamble(odocstream & os, idx_type cell,
2201                                                           bool ismulticol, bool ismultirow) const
2202 {
2203         int ret = 0;
2204         row_type const r = cellRow(cell);
2205         if (is_long_tabular && row_info[r].caption)
2206                 return ret;
2207
2208         // usual cells
2209         if (getUsebox(cell) == BOX_PARBOX)
2210                 os << '}';
2211         else if (getUsebox(cell) == BOX_MINIPAGE) {
2212                 os << "%\n\\end{minipage}";
2213                 ret += 2;
2214         }
2215         if (getRotateCell(cell)) {
2216                 os << "%\n\\end{sideways}";
2217                 ++ret;
2218         }
2219         if (ismulticol || ismultirow) {
2220                 os << '}';
2221         }
2222         return ret;
2223 }
2224
2225
2226 int Tabular::TeXLongtableHeaderFooter(odocstream & os,
2227                                          OutputParams const & runparams) const
2228 {
2229         if (!is_long_tabular)
2230                 return 0;
2231
2232         int ret = 0;
2233         // caption handling
2234         // the caption must be output before the headers
2235         if (haveLTCaption()) {
2236                 for (row_type i = 0; i < row_info.size(); ++i) {
2237                         if (row_info[i].caption) {
2238                                 ret += TeXRow(os, i, runparams);
2239                         }
2240                 }
2241         }
2242         // output first header info
2243         // first header must be output before the header, otherwise the
2244         // correct caption placement becomes really weird
2245         if (haveLTFirstHead()) {
2246                 if (endfirsthead.topDL) {
2247                         os << "\\hline\n";
2248                         ++ret;
2249                 }
2250                 for (row_type i = 0; i < row_info.size(); ++i) {
2251                         if (row_info[i].endfirsthead) {
2252                                 ret += TeXRow(os, i, runparams);
2253                         }
2254                 }
2255                 if (endfirsthead.bottomDL) {
2256                         os << "\\hline\n";
2257                         ++ret;
2258                 }
2259                 os << "\\endfirsthead\n";
2260                 ++ret;
2261         }
2262         // output header info
2263         if (haveLTHead()) {
2264                 if (endfirsthead.empty && !haveLTFirstHead()) {
2265                         os << "\\endfirsthead\n";
2266                         ++ret;
2267                 }
2268                 if (endhead.topDL) {
2269                         os << "\\hline\n";
2270                         ++ret;
2271                 }
2272                 for (row_type i = 0; i < row_info.size(); ++i) {
2273                         if (row_info[i].endhead) {
2274                                 ret += TeXRow(os, i, runparams);
2275                         }
2276                 }
2277                 if (endhead.bottomDL) {
2278                         os << "\\hline\n";
2279                         ++ret;
2280                 }
2281                 os << "\\endhead\n";
2282                 ++ret;
2283         }
2284         // output footer info
2285         if (haveLTFoot()) {
2286                 if (endfoot.topDL) {
2287                         os << "\\hline\n";
2288                         ++ret;
2289                 }
2290                 for (row_type i = 0; i < row_info.size(); ++i) {
2291                         if (row_info[i].endfoot) {
2292                                 ret += TeXRow(os, i, runparams);
2293                         }
2294                 }
2295                 if (endfoot.bottomDL) {
2296                         os << "\\hline\n";
2297                         ++ret;
2298                 }
2299                 os << "\\endfoot\n";
2300                 ++ret;
2301                 if (endlastfoot.empty && !haveLTLastFoot()) {
2302                         os << "\\endlastfoot\n";
2303                         ++ret;
2304                 }
2305         }
2306         // output lastfooter info
2307         if (haveLTLastFoot()) {
2308                 if (endlastfoot.topDL) {
2309                         os << "\\hline\n";
2310                         ++ret;
2311                 }
2312                 for (row_type i = 0; i < row_info.size(); ++i) {
2313                         if (row_info[i].endlastfoot) {
2314                                 ret += TeXRow(os, i, runparams);
2315                         }
2316                 }
2317                 if (endlastfoot.bottomDL) {
2318                         os << "\\hline\n";
2319                         ++ret;
2320                 }
2321                 os << "\\endlastfoot\n";
2322                 ++ret;
2323         }
2324         return ret;
2325 }
2326
2327
2328 bool Tabular::isValidRow(row_type row) const
2329 {
2330         if (!is_long_tabular)
2331                 return true;
2332         return !row_info[row].endhead && !row_info[row].endfirsthead
2333                 && !row_info[row].endfoot && !row_info[row].endlastfoot
2334                 && !row_info[row].caption;
2335 }
2336
2337
2338 int Tabular::TeXRow(odocstream & os, row_type i,
2339                        OutputParams const & runparams) const
2340 {
2341         idx_type cell = cellIndex(i, 0);
2342         shared_ptr<InsetTableCell> inset = cellInset(cell);
2343         Paragraph const & par = inset->paragraphs().front();
2344         string const lang = par.getParLanguage(buffer().params())->lang();
2345
2346         //output the top line
2347         int ret = TeXTopHLine(os, i, lang);
2348
2349         if (row_info[i].top_space_default) {
2350                 if (use_booktabs)
2351                         os << "\\addlinespace\n";
2352                 else
2353                         os << "\\noalign{\\vskip\\doublerulesep}\n";
2354                 ++ret;
2355         } else if(!row_info[i].top_space.zero()) {
2356                 if (use_booktabs)
2357                         os << "\\addlinespace["
2358                            << from_ascii(row_info[i].top_space.asLatexString())
2359                            << "]\n";
2360                 else {
2361                         os << "\\noalign{\\vskip"
2362                            << from_ascii(row_info[i].top_space.asLatexString())
2363                            << "}\n";
2364                 }
2365                 ++ret;
2366         }
2367         bool ismulticol = false;
2368         bool ismultirow = false;
2369         for (col_type j = 0; j < column_info.size(); ++j) {
2370                 if (isPartOfMultiRow(i, j))
2371                         os << " & "; // we need to add a further column
2372                 if (isPartOfMultiColumn(i, j) || isPartOfMultiRow(i, j))
2373                         continue;
2374                 cell = cellIndex(i, j);
2375                 ret += TeXCellPreamble(os, cell, ismulticol, ismultirow);
2376                 shared_ptr<InsetTableCell> inset = cellInset(cell);
2377
2378                 Paragraph const & par = inset->paragraphs().front();
2379                 bool rtl = par.isRTL(buffer().params())
2380                         && !par.empty()
2381                         && getPWidth(cell).zero();
2382
2383                 if (rtl) {
2384                         string const lang =
2385                                 par.getParLanguage(buffer().params())->lang();
2386                         if (lang == "farsi")
2387                                 os << "\\textFR{";
2388                         else if (lang == "arabic_arabi")
2389                                 os << "\\textAR{";
2390                         // currently, remaning RTL languages are
2391                         // arabic_arabtex and hebrew
2392                         else
2393                                 os << "\\R{";
2394                 }
2395                 // pass to the OutputParams that we are in a cell and
2396                 // which alignment we have set.
2397                 // InsetNewline needs this context information.
2398                 OutputParams newrp(runparams);
2399                 newrp.inTableCell = (getAlignment(cell) == LYX_ALIGN_BLOCK)
2400                                     ? OutputParams::PLAIN
2401                                     : OutputParams::ALIGNED;
2402                 ret += inset->latex(os, newrp);
2403                 runparams.encoding = newrp.encoding;
2404                 if (rtl)
2405                         os << '}';
2406
2407                 ret += TeXCellPostamble(os, cell, ismulticol, ismultirow);
2408                 if (cell != getLastCellInRow(i)) { // not last cell in row
2409                         os << " & ";
2410                 }
2411         }
2412         if (row_info[i].caption && !endfirsthead.empty && !haveLTFirstHead())
2413                 // if no first header and no empty first header is used,
2414                 // the caption needs to be terminated by \endfirsthead
2415                 // (bug 6057)
2416                 os << "\\endfirsthead";
2417         else
2418                 os << "\\tabularnewline";
2419         if (row_info[i].bottom_space_default) {
2420                 if (use_booktabs)
2421                         os << "\\addlinespace";
2422                 else
2423                         os << "[\\doublerulesep]";
2424         } else if (!row_info[i].bottom_space.zero()) {
2425                 if (use_booktabs)
2426                         os << "\\addlinespace";
2427                 os << '['
2428                    << from_ascii(row_info[i].bottom_space.asLatexString())
2429                    << ']';
2430         }
2431         os << '\n';
2432         ++ret;
2433
2434         //output the bottom line
2435         ret += TeXBottomHLine(os, i, lang);
2436
2437         if (row_info[i].interline_space_default) {
2438                 if (use_booktabs)
2439                         os << "\\addlinespace\n";
2440                 else
2441                         os << "\\noalign{\\vskip\\doublerulesep}\n";
2442                 ++ret;
2443         } else if (!row_info[i].interline_space.zero()) {
2444                 if (use_booktabs)
2445                         os << "\\addlinespace["
2446                            << from_ascii(row_info[i].interline_space.asLatexString())
2447                            << "]\n";
2448                 else
2449                         os << "\\noalign{\\vskip"
2450                            << from_ascii(row_info[i].interline_space.asLatexString())
2451                            << "}\n";
2452                 ++ret;
2453         }
2454         return ret;
2455 }
2456
2457
2458 int Tabular::latex(odocstream & os, OutputParams const & runparams) const
2459 {
2460         int ret = 0;
2461
2462         //+---------------------------------------------------------------------
2463         //+                      first the opening preamble                    +
2464         //+---------------------------------------------------------------------
2465
2466         if (rotate) {
2467                 os << "\\begin{sideways}\n";
2468                 ++ret;
2469         }
2470         if (is_long_tabular) {
2471                 os << "\\begin{longtable}";
2472                 switch (longtabular_alignment) {
2473                 case LYX_LONGTABULAR_ALIGN_LEFT:
2474                         os << "[l]";
2475                         break;
2476                 case LYX_LONGTABULAR_ALIGN_CENTER:
2477                         break;
2478                 case LYX_LONGTABULAR_ALIGN_RIGHT:
2479                         os << "[r]";
2480                         break;
2481                 }
2482         } else {
2483                 os << "\\begin{tabular}";
2484                 switch (tabular_valignment) {
2485                 case LYX_VALIGN_TOP:
2486                         os << "[t]";
2487                         break;
2488                 case LYX_VALIGN_MIDDLE:
2489                         break;
2490                 case LYX_VALIGN_BOTTOM:
2491                         os << "[b]";
2492                         break;
2493                 }
2494         }
2495         
2496         os << "{";
2497
2498         for (col_type i = 0; i < column_info.size(); ++i) {
2499                 if (columnLeftLine(i))
2500                         os << '|';
2501                 if (!column_info[i].align_special.empty()) {
2502                         os << column_info[i].align_special;
2503                 } else {
2504                         if (!column_info[i].p_width.zero()) {
2505                                 switch (column_info[i].alignment) {
2506                                 case LYX_ALIGN_LEFT:
2507                                         os << ">{\\raggedright}";
2508                                         break;
2509                                 case LYX_ALIGN_RIGHT:
2510                                         os << ">{\\raggedleft}";
2511                                         break;
2512                                 case LYX_ALIGN_CENTER:
2513                                         os << ">{\\centering}";
2514                                         break;
2515                                 case LYX_ALIGN_NONE:
2516                                 case LYX_ALIGN_BLOCK:
2517                                 case LYX_ALIGN_LAYOUT:
2518                                 case LYX_ALIGN_SPECIAL:
2519                                         break;
2520                                 }
2521
2522                                 switch (column_info[i].valignment) {
2523                                 case LYX_VALIGN_TOP:
2524                                         os << 'p';
2525                                         break;
2526                                 case LYX_VALIGN_MIDDLE:
2527                                         os << 'm';
2528                                         break;
2529                                 case LYX_VALIGN_BOTTOM:
2530                                         os << 'b';
2531                                         break;
2532                         }
2533                                 os << '{'
2534                                    << from_ascii(column_info[i].p_width.asLatexString())
2535                                    << '}';
2536                         } else {
2537                                 switch (column_info[i].alignment) {
2538                                 case LYX_ALIGN_LEFT:
2539                                         os << 'l';
2540                                         break;
2541                                 case LYX_ALIGN_RIGHT:
2542                                         os << 'r';
2543                                         break;
2544                                 default:
2545                                         os << 'c';
2546                                         break;
2547                                 }
2548                         } // end if else !column_info[i].p_width
2549                 } // end if else !column_info[i].align_special
2550                 if (columnRightLine(i))
2551                         os << '|';
2552         }
2553         os << "}\n";
2554         ++ret;
2555
2556         ret += TeXLongtableHeaderFooter(os, runparams);
2557
2558         //+---------------------------------------------------------------------
2559         //+                      the single row and columns (cells)            +
2560         //+---------------------------------------------------------------------
2561
2562         for (row_type i = 0; i < row_info.size(); ++i) {
2563                 if (isValidRow(i)) {
2564                         ret += TeXRow(os, i, runparams);
2565                         if (is_long_tabular && row_info[i].newpage) {
2566                                 os << "\\newpage\n";
2567                                 ++ret;
2568                         }
2569                 }
2570         }
2571
2572         //+---------------------------------------------------------------------
2573         //+                      the closing of the tabular                    +
2574         //+---------------------------------------------------------------------
2575
2576         if (is_long_tabular)
2577                 os << "\\end{longtable}";
2578         else
2579                 os << "\\end{tabular}";
2580         if (rotate) {
2581                 os << "\n\\end{sideways}";
2582                 ++ret;
2583         }
2584
2585         return ret;
2586 }
2587
2588
2589 int Tabular::docbookRow(odocstream & os, row_type row,
2590                            OutputParams const & runparams) const
2591 {
2592         int ret = 0;
2593         idx_type cell = getFirstCellInRow(row);
2594
2595         os << "<row>\n";
2596         for (col_type j = 0; j < column_info.size(); ++j) {
2597                 if (isPartOfMultiColumn(row, j))
2598                         continue;
2599
2600                 os << "<entry align=\"";
2601                 switch (getAlignment(cell)) {
2602                 case LYX_ALIGN_LEFT:
2603                         os << "left";
2604                         break;
2605                 case LYX_ALIGN_RIGHT:
2606                         os << "right";
2607                         break;
2608                 default:
2609                         os << "center";
2610                         break;
2611                 }
2612
2613                 os << "\" valign=\"";
2614                 switch (getVAlignment(cell)) {
2615                 case LYX_VALIGN_TOP:
2616                         os << "top";
2617                         break;
2618                 case LYX_VALIGN_BOTTOM:
2619                         os << "bottom";
2620                         break;
2621                 case LYX_VALIGN_MIDDLE:
2622                         os << "middle";
2623                 }
2624                 os << '"';
2625
2626                 if (isMultiColumn(cell)) {
2627                         os << " namest=\"col" << j << "\" ";
2628                         os << "nameend=\"col" << j + columnSpan(cell) - 1<< '"';
2629                 }
2630
2631                 os << '>';
2632                 ret += cellInset(cell)->docbook(os, runparams);
2633                 os << "</entry>\n";
2634                 ++cell;
2635         }
2636         os << "</row>\n";
2637         return ret;
2638 }
2639
2640
2641 int Tabular::docbook(odocstream & os, OutputParams const & runparams) const
2642 {
2643         int ret = 0;
2644
2645         //+---------------------------------------------------------------------
2646         //+                      first the opening preamble                    +
2647         //+---------------------------------------------------------------------
2648
2649         os << "<tgroup cols=\"" << column_info.size()
2650            << "\" colsep=\"1\" rowsep=\"1\">\n";
2651
2652         for (col_type i = 0; i < column_info.size(); ++i) {
2653                 os << "<colspec colname=\"col" << i << "\" align=\"";
2654                 switch (column_info[i].alignment) {
2655                 case LYX_ALIGN_LEFT:
2656                         os << "left";
2657                         break;
2658                 case LYX_ALIGN_RIGHT:
2659                         os << "right";
2660                         break;
2661                 default:
2662                         os << "center";
2663                         break;
2664                 }
2665                 os << '"';
2666                 if (runparams.flavor == OutputParams::XML)
2667                         os << '/';
2668                 os << ">\n";
2669                 ++ret;
2670         }
2671
2672         //+---------------------------------------------------------------------
2673         //+                      Long Tabular case                             +
2674         //+---------------------------------------------------------------------
2675
2676         // output caption info
2677         if (haveLTCaption()) {
2678                 os << "<caption>\n";
2679                 ++ret;
2680                 for (row_type i = 0; i < row_info.size(); ++i) {
2681                         if (row_info[i].caption) {
2682                                 ret += docbookRow(os, i, runparams);
2683                         }
2684                 }
2685                 os << "</caption>\n";
2686                 ++ret;
2687         }
2688         // output header info
2689         if (haveLTHead() || haveLTFirstHead()) {
2690                 os << "<thead>\n";
2691                 ++ret;
2692                 for (row_type i = 0; i < row_info.size(); ++i) {
2693                         if (row_info[i].endhead || row_info[i].endfirsthead) {
2694                                 ret += docbookRow(os, i, runparams);
2695                         }
2696                 }
2697                 os << "</thead>\n";
2698                 ++ret;
2699         }
2700         // output footer info
2701         if (haveLTFoot() || haveLTLastFoot()) {
2702                 os << "<tfoot>\n";
2703                 ++ret;
2704                 for (row_type i = 0; i < row_info.size(); ++i) {
2705                         if (row_info[i].endfoot || row_info[i].endlastfoot) {
2706                                 ret += docbookRow(os, i, runparams);
2707                         }
2708                 }
2709                 os << "</tfoot>\n";
2710                 ++ret;
2711         }
2712
2713         //+---------------------------------------------------------------------
2714         //+                      the single row and columns (cells)            +
2715         //+---------------------------------------------------------------------
2716
2717         os << "<tbody>\n";
2718         ++ret;
2719         for (row_type i = 0; i < row_info.size(); ++i) {
2720                 if (isValidRow(i)) {
2721                         ret += docbookRow(os, i, runparams);
2722                 }
2723         }
2724         os << "</tbody>\n";
2725         ++ret;
2726         //+---------------------------------------------------------------------
2727         //+                      the closing of the tabular                    +
2728         //+---------------------------------------------------------------------
2729
2730         os << "</tgroup>";
2731         ++ret;
2732
2733         return ret;
2734 }
2735
2736
2737 docstring Tabular::xhtmlRow(XHTMLStream & xs, row_type row,
2738                            OutputParams const & runparams) const
2739 {
2740         docstring ret;
2741         idx_type cell = getFirstCellInRow(row);
2742
2743         xs << html::StartTag("tr");
2744         for (col_type j = 0; j < column_info.size(); ++j) {
2745                 if (isPartOfMultiColumn(row, j))
2746                         continue;
2747
2748                 stringstream attr;
2749                 attr << "align='";
2750                 switch (getAlignment(cell)) {
2751                 case LYX_ALIGN_LEFT:
2752                         attr << "left";
2753                         break;
2754                 case LYX_ALIGN_RIGHT:
2755                         attr << "right";
2756                         break;
2757                 default:
2758                         attr << "center";
2759                         break;
2760                 }
2761                 attr << "'";
2762                 attr << " valign='";
2763                 switch (getVAlignment(cell)) {
2764                 case LYX_VALIGN_TOP:
2765                         attr << "top";
2766                         break;
2767                 case LYX_VALIGN_BOTTOM:
2768                         attr << "bottom";
2769                         break;
2770                 case LYX_VALIGN_MIDDLE:
2771                         attr << "middle";
2772                 }
2773                 attr << "'";
2774
2775                 if (isMultiColumn(cell))
2776                         attr << " colspan='" << columnSpan(cell) << "'";
2777
2778                 xs << html::StartTag("td", attr.str());
2779                 ret += cellInset(cell)->xhtml(xs, runparams);
2780                 xs << html::EndTag("td");
2781                 ++cell;
2782         }
2783         xs << html::EndTag("tr");
2784         return ret;
2785 }
2786
2787
2788 docstring Tabular::xhtml(XHTMLStream & xs, OutputParams const & runparams) const
2789 {
2790         docstring ret;
2791         // It's unclear to me if we need to mess with the long table stuff. 
2792         // We can borrow that too from docbook, if so.
2793
2794         xs << html::StartTag("tbody");
2795         for (row_type i = 0; i < row_info.size(); ++i) {
2796                 if (isValidRow(i)) {
2797                         ret += xhtmlRow(xs, i, runparams);
2798                 }
2799         }
2800         xs << html::EndTag("tbody");
2801         return ret;
2802 }
2803
2804
2805 bool Tabular::plaintextTopHLine(odocstream & os, row_type row,
2806                                    vector<unsigned int> const & clen) const
2807 {
2808         idx_type const fcell = getFirstCellInRow(row);
2809         idx_type const n = numberOfCellsInRow(row) + fcell;
2810         idx_type tmp = 0;
2811
2812         for (idx_type i = fcell; i < n; ++i) {
2813                 if (topLine(i)) {
2814                         ++tmp;
2815                         break;
2816                 }
2817         }
2818         if (!tmp)
2819                 return false;
2820
2821         char_type ch;
2822         for (idx_type i = fcell; i < n; ++i) {
2823                 if (topLine(i)) {
2824                         if (leftLine(i))
2825                                 os << "+-";
2826                         else
2827                                 os << "--";
2828                         ch = '-';
2829                 } else {
2830                         os << "  ";
2831                         ch = ' ';
2832                 }
2833                 col_type column = cellColumn(i);
2834                 int len = clen[column];
2835                 while (column < column_info.size() - 1
2836                        && isPartOfMultiColumn(row, ++column))
2837                         len += clen[column] + 4;
2838                 os << docstring(len, ch);
2839                 if (topLine(i)) {
2840                         if (rightLine(i))
2841                                 os << "-+";
2842                         else
2843                                 os << "--";
2844                 } else {
2845                         os << "  ";
2846                 }
2847         }
2848         os << endl;
2849         return true;
2850 }
2851
2852
2853 bool Tabular::plaintextBottomHLine(odocstream & os, row_type row,
2854                                       vector<unsigned int> const & clen) const
2855 {
2856         idx_type const fcell = getFirstCellInRow(row);
2857         idx_type const n = numberOfCellsInRow(row) + fcell;
2858         idx_type tmp = 0;
2859
2860         for (idx_type i = fcell; i < n; ++i) {
2861                 if (bottomLine(i)) {
2862                         ++tmp;
2863                         break;
2864                 }
2865         }
2866         if (!tmp)
2867                 return false;
2868
2869         char_type ch;
2870         for (idx_type i = fcell; i < n; ++i) {
2871                 if (bottomLine(i)) {
2872                         if (leftLine(i))
2873                                 os << "+-";
2874                         else
2875                                 os << "--";
2876                         ch = '-';
2877                 } else {
2878                         os << "  ";
2879                         ch = ' ';
2880                 }
2881                 col_type column = cellColumn(i);
2882                 int len = clen[column];
2883                 while (column < column_info.size() -1
2884                        && isPartOfMultiColumn(row, ++column))
2885                         len += clen[column] + 4;
2886                 os << docstring(len, ch);
2887                 if (bottomLine(i)) {
2888                         if (rightLine(i))
2889                                 os << "-+";
2890                         else
2891                                 os << "--";
2892                 } else {
2893                         os << "  ";
2894                 }
2895         }
2896         os << endl;
2897         return true;
2898 }
2899
2900
2901 void Tabular::plaintextPrintCell(odocstream & os,
2902                                OutputParams const & runparams,
2903                                idx_type cell, row_type row, col_type column,
2904                                vector<unsigned int> const & clen,
2905                                bool onlydata) const
2906 {
2907         odocstringstream sstr;
2908         cellInset(cell)->plaintext(sstr, runparams);
2909
2910         if (onlydata) {
2911                 os << sstr.str();
2912                 return;
2913         }
2914
2915         if (leftLine(cell))
2916                 os << "| ";
2917         else
2918                 os << "  ";
2919
2920         unsigned int len1 = sstr.str().length();
2921         unsigned int len2 = clen[column];
2922         while (column < column_info.size() -1
2923                && isPartOfMultiColumn(row, ++column))
2924                 len2 += clen[column] + 4;
2925         len2 -= len1;
2926
2927         switch (getAlignment(cell)) {
2928         default:
2929         case LYX_ALIGN_LEFT:
2930                 len1 = 0;
2931                 break;
2932         case LYX_ALIGN_RIGHT:
2933                 len1 = len2;
2934                 len2 = 0;
2935                 break;
2936         case LYX_ALIGN_CENTER:
2937                 len1 = len2 / 2;
2938                 len2 -= len1;
2939                 break;
2940         }
2941
2942         os << docstring(len1, ' ') << sstr.str()
2943            << docstring(len2, ' ');
2944
2945         if (rightLine(cell))
2946                 os << " |";
2947         else
2948                 os << "  ";
2949 }
2950
2951
2952 void Tabular::plaintext(odocstream & os,
2953                            OutputParams const & runparams, int const depth,
2954                            bool onlydata, char_type delim) const
2955 {
2956         // first calculate the width of the single columns
2957         vector<unsigned int> clen(column_info.size());
2958
2959         if (!onlydata) {
2960                 // first all non (real) multicolumn cells!
2961                 for (col_type j = 0; j < column_info.size(); ++j) {
2962                         clen[j] = 0;
2963                         for (row_type i = 0; i < row_info.size(); ++i) {
2964                                 idx_type cell = cellIndex(i, j);
2965                                 if (isMultiColumnReal(cell))
2966                                         continue;
2967                                 odocstringstream sstr;
2968                                 cellInset(cell)->plaintext(sstr, runparams);
2969                                 if (clen[j] < sstr.str().length())
2970                                         clen[j] = sstr.str().length();
2971                         }
2972                 }
2973                 // then all (real) multicolumn cells!
2974                 for (col_type j = 0; j < column_info.size(); ++j) {
2975                         for (row_type i = 0; i < row_info.size(); ++i) {
2976                                 idx_type cell = cellIndex(i, j);
2977                                 if (!isMultiColumnReal(cell) || isPartOfMultiColumn(i, j))
2978                                         continue;
2979                                 odocstringstream sstr;
2980                                 cellInset(cell)->plaintext(sstr, runparams);
2981                                 int len = int(sstr.str().length());
2982                                 idx_type const n = columnSpan(cell);
2983                                 for (col_type k = j; len > 0 && k < j + n - 1; ++k)
2984                                         len -= clen[k];
2985                                 if (len > int(clen[j + n - 1]))
2986                                         clen[j + n - 1] = len;
2987                         }
2988                 }
2989         }
2990         idx_type cell = 0;
2991         for (row_type i = 0; i < row_info.size(); ++i) {
2992                 if (!onlydata && plaintextTopHLine(os, i, clen))
2993                         os << docstring(depth * 2, ' ');
2994                 for (col_type j = 0; j < column_info.size(); ++j) {
2995                         if (isPartOfMultiColumn(i, j))
2996                                 continue;
2997                         if (onlydata && j > 0)
2998                                 // we don't use operator<< for single UCS4 character.
2999                                 // see explanation in docstream.h
3000                                 os.put(delim);
3001                         plaintextPrintCell(os, runparams, cell, i, j, clen, onlydata);
3002                         ++cell;
3003                 }
3004                 os << endl;
3005                 if (!onlydata) {
3006                         os << docstring(depth * 2, ' ');
3007                         if (plaintextBottomHLine(os, i, clen))
3008                                 os << docstring(depth * 2, ' ');
3009                 }
3010         }
3011 }
3012
3013
3014 shared_ptr<InsetTableCell> Tabular::cellInset(idx_type cell) const
3015 {
3016         return cell_info[cellRow(cell)][cellColumn(cell)].inset;
3017 }
3018
3019
3020 shared_ptr<InsetTableCell> Tabular::cellInset(row_type row,
3021                                                col_type column) const
3022 {
3023         return cell_info[row][column].inset;
3024 }
3025
3026
3027 void Tabular::setCellInset(row_type row, col_type column,
3028                               shared_ptr<InsetTableCell> ins) const
3029 {
3030         CellData & cd = cell_info[row][column];
3031         cd.inset = ins;
3032 }
3033
3034
3035 void Tabular::validate(LaTeXFeatures & features) const
3036 {
3037         features.require("NeedTabularnewline");
3038         if (use_booktabs)
3039                 features.require("booktabs");
3040         if (is_long_tabular)
3041                 features.require("longtable");
3042         if (needRotating())
3043                 features.require("rotating");
3044         for (idx_type cell = 0; cell < numberofcells; ++cell) {
3045                 if (isMultiRow(cell))
3046                         features.require("multirow");
3047                 if (getVAlignment(cell) != LYX_VALIGN_TOP
3048                     || !getPWidth(cell).zero())
3049                         features.require("array");
3050                 cellInset(cell)->validate(features);
3051         }
3052 }
3053
3054
3055 Tabular::BoxType Tabular::useParbox(idx_type cell) const
3056 {
3057         ParagraphList const & parlist = cellInset(cell)->paragraphs();
3058         ParagraphList::const_iterator cit = parlist.begin();
3059         ParagraphList::const_iterator end = parlist.end();
3060
3061         for (; cit != end; ++cit)
3062                 for (int i = 0; i < cit->size(); ++i)
3063                         if (cit->isNewline(i))
3064                                 return BOX_PARBOX;
3065
3066         return BOX_NONE;
3067 }
3068
3069
3070 /////////////////////////////////////////////////////////////////////
3071 //
3072 // InsetTableCell
3073 //
3074 /////////////////////////////////////////////////////////////////////
3075
3076 InsetTableCell::InsetTableCell(Buffer * buf)
3077         : InsetText(buf, InsetText::PlainLayout), isFixedWidth(false),
3078           contentAlign(LYX_ALIGN_CENTER)
3079 {}
3080
3081
3082 bool InsetTableCell::forcePlainLayout(idx_type) const
3083 {
3084         return !isFixedWidth;
3085 }
3086
3087
3088 bool InsetTableCell::allowParagraphCustomization(idx_type) const
3089 {
3090         return isFixedWidth;
3091 }
3092
3093
3094 bool InsetTableCell::getStatus(Cursor & cur, FuncRequest const & cmd,
3095         FuncStatus & status) const
3096 {
3097         bool enabled;
3098         switch (cmd.action) {
3099         case LFUN_LAYOUT:
3100                 enabled = !forcePlainLayout();
3101                 break;
3102         case LFUN_LAYOUT_PARAGRAPH:
3103                 enabled = allowParagraphCustomization();
3104                 break;
3105         default:
3106                 return InsetText::getStatus(cur, cmd, status);
3107         }
3108         status.setEnabled(enabled);
3109         return true;
3110 }
3111
3112 docstring InsetTableCell::asString(bool intoInsets) 
3113 {
3114         docstring retval;
3115         if (paragraphs().empty())
3116                 return retval;
3117         ParagraphList::const_iterator it = paragraphs().begin();
3118         ParagraphList::const_iterator en = paragraphs().end();
3119         bool first = true;
3120         for (; it != en; ++it) {
3121                 if (!first)
3122                         retval += "\n";
3123                 else
3124                         first = false;
3125                 retval += it->asString(intoInsets ? AS_STR_INSETS : AS_STR_NONE);
3126         }
3127         return retval;
3128 }
3129
3130
3131 docstring InsetTableCell::xhtml(XHTMLStream & xs, OutputParams const & rp) const
3132 {
3133         if (!isFixedWidth)
3134                 return InsetText::insetAsXHTML(xs, rp, InsetText::JustText);
3135         return InsetText::xhtml(xs, rp);
3136 }
3137
3138
3139
3140 /////////////////////////////////////////////////////////////////////
3141 //
3142 // InsetTabular
3143 //
3144 /////////////////////////////////////////////////////////////////////
3145
3146 InsetTabular::InsetTabular(Buffer * buf, row_type rows,
3147                            col_type columns)
3148         : Inset(buf), tabular(buf, max(rows, row_type(1)), max(columns, col_type(1))), scx_(0), 
3149         rowselect_(false), colselect_(false)
3150 {
3151 }
3152
3153
3154 InsetTabular::InsetTabular(InsetTabular const & tab)
3155         : Inset(tab), tabular(tab.tabular),  scx_(0)
3156 {
3157 }
3158
3159
3160 InsetTabular::~InsetTabular()
3161 {
3162         hideDialogs("tabular", this);
3163 }
3164
3165
3166 void InsetTabular::setBuffer(Buffer & buf)
3167 {
3168         tabular.setBuffer(buf);
3169         Inset::setBuffer(buf);
3170 }
3171
3172
3173 bool InsetTabular::insetAllowed(InsetCode code) const
3174 {
3175         if (code == MATHMACRO_CODE
3176                 || (code == CAPTION_CODE && !tabular.is_long_tabular))
3177                 return false;
3178
3179         return true;
3180 }
3181
3182
3183 void InsetTabular::write(ostream & os) const
3184 {
3185         os << "Tabular" << endl;
3186         tabular.write(os);
3187 }
3188
3189
3190 docstring InsetTabular::contextMenu(BufferView const &, int, int) const
3191 {
3192         // FIXME: depending on the selection state, we could offer a different menu.
3193         return from_ascii("context-tabular");
3194 }
3195
3196
3197 void InsetTabular::read(Lexer & lex)
3198 {
3199         //bool const old_format = (lex.getString() == "\\LyXTable");
3200
3201         tabular.read(lex);
3202
3203         //if (old_format)
3204         //      return;
3205
3206         lex.next();
3207         string token = lex.getString();
3208         while (lex && token != "\\end_inset") {
3209                 lex.next();
3210                 token = lex.getString();
3211         }
3212         if (!lex)
3213                 lex.printError("Missing \\end_inset at this point. ");
3214 }
3215
3216
3217 int InsetTabular::rowFromY(Cursor & cur, int y) const
3218 {
3219         // top y coordinate of tabular
3220         int h = yo(cur.bv()) - tabular.rowAscent(0);
3221         size_t nrows = tabular.row_info.size();
3222         row_type r = 0;
3223         for (; r < nrows && y > h; ++r)
3224                 h += tabular.rowAscent(r) + tabular.rowDescent(r)
3225                 + tabular.interRowSpace(r);
3226
3227         return r - 1;
3228 }
3229
3230
3231 int InsetTabular::columnFromX(Cursor & cur, int x) const
3232 {
3233         // left x coordinate of tabular
3234         int w = xo(cur.bv()) + ADD_TO_TABULAR_WIDTH;
3235         size_t ncols = tabular.column_info.size();
3236         col_type c = 0;
3237         for (; c < ncols && x > w; ++c)
3238                 w += tabular.columnWidth(c);
3239         return c - 1;
3240 }
3241
3242
3243 void InsetTabular::metrics(MetricsInfo & mi, Dimension & dim) const
3244 {
3245         //lyxerr << "InsetTabular::metrics: " << mi.base.bv << " width: " <<
3246         //      mi.base.textwidth << "\n";
3247         if (!mi.base.bv) {
3248                 LYXERR0("need bv");
3249                 LASSERT(false, /**/);
3250         }
3251
3252         for (row_type i = 0; i < tabular.row_info.size(); ++i) {
3253                 int maxAsc = 0;
3254                 int maxDesc = 0;
3255                 for (col_type j = 0; j < tabular.column_info.size(); ++j) {
3256                         if (tabular.isPartOfMultiColumn(i, j)
3257                                 || tabular.isPartOfMultiRow(i, j))
3258                                 // multicolumn or multirow cell, but not first one
3259                                 continue;
3260                         idx_type const cell = tabular.cellIndex(i, j);
3261                         Dimension dim;
3262                         MetricsInfo m = mi;
3263                         Length p_width;
3264                         if (tabular.cell_info[i][j].multicolumn ==
3265                                 Tabular::CELL_BEGIN_OF_MULTICOLUMN)
3266                                 p_width = tabular.cellInfo(cell).p_width;
3267                         else
3268                                 p_width = tabular.column_info[j].p_width;
3269                         if (!p_width.zero())
3270                                 m.base.textwidth = p_width.inPixels(mi.base.textwidth);
3271                         tabular.cellInset(cell)->metrics(m, dim);
3272                         if (!p_width.zero())
3273                                 dim.wid = m.base.textwidth;
3274                         tabular.setCellWidth(cell, dim.wid);
3275                         maxAsc  = max(maxAsc, dim.asc);
3276                         maxDesc = max(maxDesc, dim.des);
3277                 }
3278                 int const top_space = tabular.row_info[i].top_space_default ?
3279                         default_line_space :
3280                         tabular.row_info[i].top_space.inPixels(mi.base.textwidth);
3281                 tabular.setRowAscent(i, maxAsc + ADD_TO_HEIGHT + top_space);
3282                 int const bottom_space = tabular.row_info[i].bottom_space_default ?
3283                         default_line_space :
3284                         tabular.row_info[i].bottom_space.inPixels(mi.base.textwidth);
3285                 tabular.setRowDescent(i, maxDesc + ADD_TO_HEIGHT + bottom_space);
3286         }
3287         tabular.updateColumnWidths();
3288         dim.asc = tabular.rowAscent(0);
3289         dim.des = tabular.height() - dim.asc;
3290         dim.wid = tabular.width() + 2 * ADD_TO_TABULAR_WIDTH;
3291 }
3292
3293 bool InsetTabular::isCellSelected(Cursor & cur, row_type row, col_type col) 
3294         const
3295 {
3296         if (&cur.inset() == this && cur.selection()) {
3297                 if (cur.selIsMultiCell()) {
3298                         row_type rs, re;
3299                         col_type cs, ce;
3300                         getSelection(cur, rs, re, cs, ce);
3301                         
3302                         if (col >= cs && col <= ce && row >= rs && row <= re)
3303                                 return true;
3304                 } else 
3305                         if (col == tabular.cellColumn(cur.idx()) 
3306                                 && row == tabular.cellRow(cur.idx())) {
3307                         CursorSlice const & beg = cur.selBegin();
3308                         CursorSlice const & end = cur.selEnd();
3309
3310                         if ((end.lastpos() > 0 || end.lastpit() > 0)
3311                                   && end.pos() == end.lastpos() && beg.pos() == 0
3312                                   && end.pit() == end.lastpit() && beg.pit() == 0)
3313                                 return true;
3314                 }
3315         }
3316         return false;
3317 }
3318
3319
3320 void InsetTabular::draw(PainterInfo & pi, int x, int y) const
3321 {
3322         x += scx_ + ADD_TO_TABULAR_WIDTH;
3323
3324         BufferView * bv = pi.base.bv;
3325         Cursor & cur = pi.base.bv->cursor();
3326         resetPos(cur);
3327
3328         // FIXME: As the full background is painted in drawSelection(),
3329         // we have no choice but to do a full repaint for the Text cells.
3330         pi.full_repaint = true;
3331
3332         bool const original_selection_state = pi.selected;
3333
3334         idx_type idx = 0;
3335         first_visible_cell = Tabular::npos;
3336         for (row_type i = 0; i < tabular.row_info.size(); ++i) {
3337                 int nx = x;
3338                 for (col_type j = 0; j < tabular.column_info.size(); ++j) {
3339                         if (tabular.isPartOfMultiColumn(i, j))
3340                                 continue;
3341                         
3342                         idx = tabular.cellIndex(i, j);
3343                         
3344                         if (tabular.isPartOfMultiRow(i, j)) {
3345                                 nx += tabular.columnWidth(idx);
3346                                 continue;
3347                         }
3348
3349                         if (first_visible_cell == Tabular::npos)
3350                                 first_visible_cell = idx;
3351
3352                         pi.selected |= isCellSelected(cur, i, j);
3353                         int const cx = nx + tabular.textHOffset(idx);
3354                         int const cy = y  + tabular.textVOffset(idx);
3355                         // Cache the Inset position.
3356                         bv->coordCache().insets().add(cell(idx).get(), cx, y);
3357                         cell(idx)->draw(pi, cx, cy);
3358                         drawCellLines(pi.pain, nx, y, i, idx, pi.change_);
3359                         nx += tabular.columnWidth(idx);
3360                         pi.selected = original_selection_state;
3361                 }
3362
3363                 if (i + 1 < tabular.row_info.size())
3364                         y += tabular.rowDescent(i) + tabular.rowAscent(i + 1)
3365                              + tabular.interRowSpace(i + 1);
3366         }
3367 }
3368
3369
3370 void InsetTabular::drawSelection(PainterInfo & pi, int x, int y) const
3371 {
3372         Cursor & cur = pi.base.bv->cursor();
3373         resetPos(cur);
3374
3375         x += scx_ + ADD_TO_TABULAR_WIDTH;
3376
3377         // FIXME: it is wrong to completely paint the background
3378         // if we want to do single row painting.
3379
3380         // Paint background of current tabular
3381         int const w = tabular.width();
3382         int const h = tabular.height();
3383         int yy = y - tabular.rowAscent(0);
3384         pi.pain.fillRectangle(x, yy, w, h, pi.backgroundColor(this));
3385
3386         if (!cur.selection())
3387                 return;
3388         if (&cur.inset() != this)
3389                 return;
3390
3391         //resetPos(cur);
3392
3393         bool const full_cell_selected = isCellSelected(cur,
3394                 tabular.cellRow(cur.idx()), tabular.cellColumn(cur.idx()));
3395
3396         if (cur.selIsMultiCell() || full_cell_selected) {
3397                 y -= tabular.rowAscent(0);
3398                 for (row_type r = 0; r < tabular.row_info.size(); ++r) {
3399                         int xx = x;
3400                         for (col_type c = 0; c < tabular.column_info.size(); ++c) {
3401                                 if (tabular.isPartOfMultiColumn(r, c))
3402                                         continue;
3403
3404                                 idx_type const cell = tabular.cellIndex(r, c);
3405
3406                                 if (tabular.isPartOfMultiRow(r, c)) {
3407                                         xx += tabular.columnWidth(cell);
3408                                         continue;
3409                                 }
3410                                 int const w = tabular.columnWidth(cell);
3411                                 int const h = tabular.rowHeight(cell);
3412                                 if (isCellSelected(cur, r, c))
3413                                         pi.pain.fillRectangle(xx, y, w, h, Color_selection);
3414                                 xx += w;
3415                         }
3416                         if (r + 1 < tabular.row_info.size())
3417                                 y += tabular.rowDescent(r) + tabular.rowAscent(r + 1)
3418                                      + tabular.interRowSpace(r + 1);
3419                 }
3420
3421         } else {
3422                 x += cellXPos(cur.idx());
3423                 x += tabular.textHOffset(cur.idx());
3424                 cell(cur.idx())->drawSelection(pi, x, 0 /* ignored */);
3425         }
3426 }
3427
3428
3429 void InsetTabular::drawCellLines(Painter & pain, int x, int y,
3430                                  row_type row, idx_type cell, Change const & change) const
3431 {
3432         y = y - tabular.rowAscent(row);
3433         int const w = tabular.columnWidth(cell);
3434         int const h = tabular.rowHeight(cell);
3435         bool on_off = false;
3436         Color col = Color_tabularline;
3437         Color onoffcol = Color_tabularonoffline;
3438
3439         if (change.changed()) {
3440                 col = change.color();
3441                 onoffcol = change.color();
3442         }
3443
3444         bool topalreadydrawn = row > 0 && !tabular.rowTopLine(row) 
3445                 && tabular.bottomLine(tabular.cellAbove(cell));
3446
3447         if (!topalreadydrawn) {
3448                 on_off = !tabular.topLine(cell);
3449                 pain.line(x, y, x + w, y,
3450                         on_off ? onoffcol : col,
3451                         on_off ? Painter::line_onoffdash : Painter::line_solid);
3452         }
3453         on_off = !tabular.bottomLine(cell);
3454         pain.line(x, y + h, x + w, y + h,
3455                 on_off ? onoffcol : col,
3456                 on_off ? Painter::line_onoffdash : Painter::line_solid);
3457
3458         col_type const column = tabular.cellColumn(cell);
3459         bool leftalreadydrawn = column > 0  && !tabular.leftLine(cell)
3460                 && tabular.rightLine(tabular.cellIndex(row, column - 1));
3461
3462         if (!leftalreadydrawn) {
3463                 on_off = !tabular.leftLine(cell);
3464                 pain.line(x, y, x, y + h,
3465                         on_off ? onoffcol : col,
3466                         on_off ? Painter::line_onoffdash : Painter::line_solid);
3467         }
3468         on_off = !tabular.rightLine(cell);
3469         pain.line(x + w - tabular.interColumnSpace(cell), y,
3470                 x + w - tabular.interColumnSpace(cell), y + h,
3471                 on_off ? onoffcol : col,
3472                 on_off ? Painter::line_onoffdash : Painter::line_solid);
3473 }
3474
3475
3476 void InsetTabular::edit(Cursor & cur, bool front, EntryDirection)
3477 {
3478         //lyxerr << "InsetTabular::edit: " << this << endl;
3479         cur.finishUndo();
3480         cur.setSelection(false);
3481         cur.push(*this);
3482         if (front) {
3483                 if (isRightToLeft(cur))
3484                         cur.idx() = tabular.getLastCellInRow(0);
3485                 else
3486                         cur.idx() = 0;
3487                 cur.pit() = 0;
3488                 cur.pos() = 0;
3489         } else {
3490                 if (isRightToLeft(cur))
3491                         cur.idx() = tabular.getFirstCellInRow(tabular.row_info.size() - 1);
3492                 else
3493                         cur.idx() = tabular.numberofcells - 1;
3494                 cur.pit() = 0;
3495                 cur.pos() = cur.lastpos(); // FIXME crude guess
3496         }
3497         cur.setCurrentFont();
3498         // FIXME: this accesses the position cache before it is initialized
3499         //resetPos(cur);
3500         //cur.bv().fitCursor();
3501 }
3502
3503
3504 void InsetTabular::updateBuffer(ParIterator const & it, UpdateType utype)
3505 {
3506         // In a longtable, tell captions what the current float is
3507         Counters & cnts = buffer().masterBuffer()->params().documentClass().counters();
3508         string const saveflt = cnts.current_float();
3509         if (tabular.is_long_tabular)
3510                 cnts.current_float("table");
3511
3512         ParIterator it2 = it;
3513         it2.forwardPos();
3514         size_t const end = it2.nargs();
3515         for ( ; it2.idx() < end; it2.top().forwardIdx())
3516                 buffer().updateBuffer(it2, utype);
3517
3518         //reset afterwards
3519         if (tabular.is_long_tabular)
3520                 cnts.current_float(saveflt);
3521 }
3522
3523
3524 void InsetTabular::addToToc(DocIterator const & cpit)
3525 {
3526         DocIterator dit = cpit;
3527         dit.forwardPos();
3528         size_t const end = dit.nargs();
3529         for ( ; dit.idx() < end; dit.top().forwardIdx())
3530                 cell(dit.idx())->addToToc(dit);
3531 }
3532
3533
3534 void InsetTabular::doDispatch(Cursor & cur, FuncRequest & cmd)
3535 {
3536         LYXERR(Debug::DEBUG, "# InsetTabular::doDispatch: cmd: " << cmd
3537                              << "\n  cur:" << cur);
3538         CursorSlice sl = cur.top();
3539         Cursor & bvcur = cur.bv().cursor();
3540
3541         switch (cmd.action) {
3542
3543         case LFUN_MOUSE_PRESS: {
3544                 //lyxerr << "# InsetTabular::MousePress\n" << cur.bv().cursor() << endl;
3545                 // select row
3546                 if (cmd.x < xo(cur.bv()) + ADD_TO_TABULAR_WIDTH
3547                         || cmd.x > xo(cur.bv()) + tabular.width()) {
3548                         row_type r = rowFromY(cur, cmd.y);
3549                         cur.idx() = tabular.getFirstCellInRow(r);
3550                         cur.pos() = 0;
3551                         cur.resetAnchor();
3552                         cur.idx() = tabular.getLastCellInRow(r);
3553                         cur.pos() = cur.lastpos();
3554                         cur.setSelection(true);
3555                         bvcur = cur; 
3556                         rowselect_ = true;
3557                         break;
3558                 }
3559                 // select column
3560                 int const y0 = yo(cur.bv()) - tabular.rowAscent(0);
3561                 if (cmd.y < y0 + ADD_TO_TABULAR_WIDTH 
3562                         || cmd.y > y0 + tabular.height()) {
3563                         col_type c = columnFromX(cur, cmd.x);
3564                         cur.idx() = tabular.cellIndex(0, c);
3565                         cur.pos() = 0;
3566                         cur.resetAnchor();
3567                         cur.idx() = tabular.cellIndex(tabular.row_info.size() - 1, c);
3568                         cur.pos() = cur.lastpos();
3569                         cur.setSelection(true);
3570                         bvcur = cur; 
3571                         colselect_ = true;
3572                         break;
3573                 }
3574                 // do not reset cursor/selection if we have selected
3575                 // some cells (bug 2715).
3576                 if (cmd.button() == mouse_button::button3
3577                     && &bvcur.selBegin().inset() == this 
3578                     && bvcur.selIsMultiCell()) 
3579                         ;
3580                 else
3581                         // Let InsetTableCell do it
3582                         cell(cur.idx())->dispatch(cur, cmd);
3583                 break;
3584         }
3585         case LFUN_MOUSE_MOTION:
3586                 //lyxerr << "# InsetTabular::MouseMotion\n" << bvcur << endl;
3587                 if (cmd.button() == mouse_button::button1) {
3588                         // only accept motions to places not deeper nested than the real anchor
3589                         if (!bvcur.anchor_.hasPart(cur)) {
3590                                 cur.undispatched();
3591                                 break;
3592                         }
3593                         // select (additional) row
3594                         if (rowselect_) {
3595                                 row_type r = rowFromY(cur, cmd.y);
3596                                 cur.idx() = tabular.getLastCellInRow(r);
3597                                 // we need to reset the cursor's pit and pos now, as the old ones
3598                                 // may no longer be valid.
3599                                 cur.pit() = 0;
3600                                 cur.pos() = 0;
3601                                 bvcur.setCursor(cur);
3602                                 bvcur.setSelection(true);
3603                                 break;
3604                         }
3605                         // select (additional) column
3606                         if (colselect_) {
3607                                 col_type c = columnFromX(cur, cmd.x);
3608                                 cur.idx() = tabular.cellIndex(tabular.row_info.size() - 1, c);
3609                                 // we need to reset the cursor's pit and pos now, as the old ones
3610                                 // may no longer be valid.
3611                                 cur.pit() = 0;
3612                                 cur.pos() = 0;
3613                                 bvcur.setCursor(cur);
3614                                 bvcur.setSelection(true);
3615                                 break;
3616                         }
3617                         // only update if selection changes
3618                         if (bvcur.idx() == cur.idx() &&
3619                                 !(bvcur.anchor_.idx() == cur.idx() && bvcur.pos() != cur.pos()))
3620                                 cur.noUpdate();
3621                         setCursorFromCoordinates(cur, cmd.x, cmd.y);
3622                         bvcur.setCursor(cur);
3623                         bvcur.setSelection(true);
3624                         // if this is a multicell selection, we just set the cursor to
3625                         // the beginning of the cell's text.
3626                         if (bvcur.selIsMultiCell()) {
3627                                 bvcur.pit() = bvcur.lastpit();
3628                                 bvcur.pos() = bvcur.lastpos();
3629                         }
3630                 }
3631                 break;
3632
3633         case LFUN_MOUSE_RELEASE:
3634                 rowselect_ = false;
3635                 colselect_ = false;
3636                 break;
3637
3638         case LFUN_CELL_BACKWARD:
3639                 movePrevCell(cur);
3640                 cur.setSelection(false);
3641                 break;
3642
3643         case LFUN_CELL_FORWARD:
3644                 moveNextCell(cur);
3645                 cur.setSelection(false);
3646                 break;
3647
3648         case LFUN_CHAR_FORWARD_SELECT:
3649         case LFUN_CHAR_FORWARD:
3650         case LFUN_CHAR_BACKWARD_SELECT:
3651         case LFUN_CHAR_BACKWARD:
3652         case LFUN_CHAR_RIGHT_SELECT:
3653         case LFUN_CHAR_RIGHT:
3654         case LFUN_CHAR_LEFT_SELECT:
3655         case LFUN_CHAR_LEFT: {
3656                 // determine whether we move to next or previous cell, where to enter 
3657                 // the new cell from, and which command to "finish" (i.e., exit the
3658                 // inset) with:
3659                 bool next_cell;
3660                 EntryDirection entry_from = ENTRY_DIRECTION_IGNORE;
3661                 FuncCode finish_lfun;
3662
3663                 if (cmd.action == LFUN_CHAR_FORWARD 
3664                                 || cmd.action == LFUN_CHAR_FORWARD_SELECT) {
3665                         next_cell = true;
3666                         finish_lfun = LFUN_FINISHED_FORWARD;
3667                 }
3668                 else if (cmd.action == LFUN_CHAR_BACKWARD
3669                                 || cmd.action == LFUN_CHAR_BACKWARD_SELECT) {
3670                         next_cell = false;
3671                         finish_lfun = LFUN_FINISHED_BACKWARD;
3672                 }
3673                 // LEFT or RIGHT commands --- the interpretation will depend on the 
3674                 // table's direction.
3675                 else {
3676                         bool const right = cmd.action == LFUN_CHAR_RIGHT
3677                                 || cmd.action == LFUN_CHAR_RIGHT_SELECT;
3678                         next_cell = isRightToLeft(cur) != right;
3679                         
3680                         if (lyxrc.visual_cursor)
3681                                 entry_from = right ? ENTRY_DIRECTION_LEFT:ENTRY_DIRECTION_RIGHT;
3682
3683                         finish_lfun = right ? LFUN_FINISHED_RIGHT : LFUN_FINISHED_LEFT;
3684                 }
3685
3686                 bool const select = cmd.action == LFUN_CHAR_FORWARD_SELECT ||
3687                     cmd.action == LFUN_CHAR_BACKWARD_SELECT ||
3688                     cmd.action == LFUN_CHAR_RIGHT_SELECT ||
3689                     cmd.action == LFUN_CHAR_LEFT_SELECT;
3690
3691                 // If we have a multicell selection or we're 
3692                 // not doing some LFUN_*_SELECT thing anyway...
3693                 if (!cur.selIsMultiCell() || !select) {
3694                         col_type const c = tabular.cellColumn(cur.idx());
3695                         row_type const r = tabular.cellRow(cur.idx());
3696                         // Are we trying to select the whole cell and is the whole cell 
3697                         // not yet selected?
3698                         bool const select_whole = select && !isCellSelected(cur, r, c) &&
3699                                 ((next_cell && cur.pit() == cur.lastpit() 
3700                                 && cur.pos() == cur.lastpos())
3701                                 || (!next_cell && cur.pit() == 0 && cur.pos() == 0));
3702
3703                         bool const empty_cell = cur.lastpos() == 0 && cur.lastpit() == 0;
3704
3705                         // ...try to dispatch to the cell's inset.
3706                         cell(cur.idx())->dispatch(cur, cmd);
3707
3708                         // When we already have a selection we want to select the whole cell
3709                         // before going to the next cell.
3710                         if (select_whole && !empty_cell){
3711                                 getText(cur.idx())->selectAll(cur);
3712                                 cur.dispatched();
3713                                 break;
3714                         }
3715
3716                         // FIXME: When we support the selection of an empty cell, remove 
3717                         // the !empty_cell from this condition. For now we jump to the next
3718                         // cell if the current cell is empty.
3719                         if (cur.result().dispatched() && !empty_cell)
3720                                 break;
3721                 }
3722
3723                 // move to next/prev cell, as appropriate
3724                 // note that we will always do this if we're selecting and we have
3725                 // a multicell selection
3726                 LYXERR(Debug::RTL, "entering " << (next_cell ? "next" : "previous")
3727                         << " cell from: " << int(entry_from));
3728                 if (next_cell)
3729                         moveNextCell(cur, entry_from);
3730                 else
3731                         movePrevCell(cur, entry_from);
3732                 // if we're exiting the table, call the appropriate FINISHED lfun
3733                 if (sl == cur.top())
3734                         cmd = FuncRequest(finish_lfun);
3735                 else
3736                         cur.dispatched();
3737                 break;
3738
3739         }
3740
3741         case LFUN_DOWN_SELECT:
3742         case LFUN_DOWN:
3743                 if (!(cur.selection() && cur.selIsMultiCell()))
3744                         cell(cur.idx())->dispatch(cur, cmd);
3745                 
3746                 cur.dispatched(); // override the cell's decision
3747                 if (sl == cur.top()) {
3748                         // if our Text didn't do anything to the cursor
3749                         // then we try to put the cursor into the cell below
3750                         // setting also the right targetX.
3751                         cur.selHandle(cmd.action == LFUN_DOWN_SELECT);
3752                         if (tabular.cellRow(cur.idx()) != tabular.row_info.size() - 1) {
3753                                 cur.idx() = tabular.cellBelow(cur.idx());
3754                                 cur.pit() = 0;
3755                                 TextMetrics const & tm =
3756                                         cur.bv().textMetrics(cell(cur.idx())->getText(0));
3757                                 cur.pos() = tm.x2pos(cur.pit(), 0, cur.targetX());
3758                                 cur.setCurrentFont();
3759                         }
3760                 }
3761                 if (sl == cur.top()) {
3762                         // we trick it to go to forward after leaving the
3763                         // tabular.
3764                         cmd = FuncRequest(LFUN_FINISHED_FORWARD);
3765                         cur.undispatched();
3766                 }
3767                 if (cur.selIsMultiCell()) {
3768                         cur.pit() = cur.lastpit();
3769                         cur.pos() = cur.lastpos();
3770                         cur.setCurrentFont();
3771                         return;
3772                 }
3773                 break;
3774
3775         case LFUN_UP_SELECT:
3776         case LFUN_UP:
3777                 if (!(cur.selection() && cur.selIsMultiCell()))
3778                         cell(cur.idx())->dispatch(cur, cmd);
3779                 cur.dispatched(); // override the cell's decision
3780                 if (sl == cur.top()) {
3781                         // if our Text didn't do anything to the cursor
3782                         // then we try to put the cursor into the cell above
3783                         // setting also the right targetX.
3784                         cur.selHandle(cmd.action == LFUN_UP_SELECT);
3785                         if (tabular.cellRow(cur.idx()) != 0) {
3786                                 cur.idx() = tabular.cellAbove(cur.idx());
3787                                 cur.pit() = cur.lastpit();
3788                                 Text const * text = cell(cur.idx())->getText(0);
3789                                 TextMetrics const & tm = cur.bv().textMetrics(text);
3790                                 ParagraphMetrics const & pm =
3791                                         tm.parMetrics(cur.lastpit());
3792                                 cur.pos() = tm.x2pos(cur.pit(), pm.rows().size()-1, cur.targetX());
3793                                 cur.setCurrentFont();
3794                         }
3795                 }
3796                 if (sl == cur.top()) {
3797                         cmd = FuncRequest(LFUN_UP);
3798                         cur.undispatched();
3799                 }
3800                 if (cur.selIsMultiCell()) {
3801                         cur.pit() = 0;
3802                         cur.pos() = cur.lastpos();
3803                         cur.setCurrentFont();
3804                         return;
3805                 }
3806                 break;
3807
3808 //      case LFUN_SCREEN_DOWN: {
3809 //              //if (hasSelection())
3810 //              //      cur.selection() = false;
3811 //              col_type const col = tabular.cellColumn(cur.idx());
3812 //              int const t =   cur.bv().top_y() + cur.bv().height();
3813 //              if (t < yo() + tabular.getHeightOfTabular()) {
3814 //                      cur.bv().scrollDocView(t);
3815 //                      cur.idx() = tabular.cellBelow(first_visible_cell) + col;
3816 //              } else {
3817 //                      cur.idx() = tabular.getFirstCellInRow(tabular.rows() - 1) + col;
3818 //              }
3819 //              cur.par() = 0;
3820 //              cur.pos() = 0;
3821 //              break;
3822 //      }
3823 //
3824 //      case LFUN_SCREEN_UP: {
3825 //              //if (hasSelection())
3826 //              //      cur.selection() = false;
3827 //              col_type const col = tabular.cellColumn(cur.idx());
3828 //              int const t =   cur.bv().top_y() + cur.bv().height();
3829 //              if (yo() < 0) {
3830 //                      cur.bv().scrollDocView(t);
3831 //                      if (yo() > 0)
3832 //                              cur.idx() = col;
3833 //                      else
3834 //                              cur.idx() = tabular.cellBelow(first_visible_cell) + col;
3835 //              } else {
3836 //                      cur.idx() = col;
3837 //              }
3838 //              cur.par() = cur.lastpar();
3839 //              cur.pos() = cur.lastpos();
3840 //              break;
3841 //      }
3842
3843         case LFUN_LAYOUT_TABULAR:
3844                 cur.bv().showDialog("tabular");
3845                 break;
3846
3847         case LFUN_INSET_MODIFY:
3848                 if (!tabularFeatures(cur, to_utf8(cmd.argument())))
3849                         cur.undispatched();
3850                 break;
3851
3852         // insert file functions
3853         case LFUN_FILE_INSERT_PLAINTEXT_PARA:
3854         case LFUN_FILE_INSERT_PLAINTEXT:
3855                 // FIXME UNICODE
3856                 if (FileName::isAbsolute(to_utf8(cmd.argument()))) {
3857                         docstring const tmpstr = cur.bv().contentsOfPlaintextFile(
3858                                 FileName(to_utf8(cmd.argument())));
3859                         if (tmpstr.empty())
3860                                 break;
3861                         cur.recordUndoInset(INSERT_UNDO);
3862                         if (insertPlaintextString(cur.bv(), tmpstr, false)) {
3863                                 // content has been replaced,
3864                                 // so cursor might be invalid
3865                                 cur.pos() = cur.lastpos();
3866                                 cur.pit() = cur.lastpit();
3867                                 bvcur.setCursor(cur);
3868                         } else
3869                                 cur.undispatched();
3870                 }
3871                 break;
3872
3873         case LFUN_CUT:
3874                 if (cur.selIsMultiCell()) {
3875                         if (copySelection(cur)) {
3876                                 cur.recordUndoInset(DELETE_UNDO);
3877                                 cutSelection(cur);
3878                         }
3879                 } else
3880                         cell(cur.idx())->dispatch(cur, cmd);
3881                 break;
3882
3883         case LFUN_SELF_INSERT:
3884                 if (cur.selIsMultiCell()) {
3885                         cur.recordUndoInset(DELETE_UNDO);
3886                         cutSelection(cur);
3887                 }
3888                 cell(cur.idx())->dispatch(cur, cmd);
3889                 break;
3890
3891         case LFUN_CHAR_DELETE_BACKWARD:
3892         case LFUN_CHAR_DELETE_FORWARD:
3893                 if (cur.selIsMultiCell()) {
3894                         cur.recordUndoInset(DELETE_UNDO);
3895                         cutSelection(cur);
3896                 } else
3897                         cell(cur.idx())->dispatch(cur, cmd);
3898                 break;
3899
3900         case LFUN_COPY:
3901                 if (!cur.selection())
3902                         break;
3903                 if (cur.selIsMultiCell()) {
3904                         cur.finishUndo();
3905                         copySelection(cur);
3906                 } else
3907                         cell(cur.idx())->dispatch(cur, cmd);
3908                 break;
3909
3910         case LFUN_CLIPBOARD_PASTE:
3911         case LFUN_PRIMARY_SELECTION_PASTE: {
3912                 docstring const clip = (cmd.action == LFUN_CLIPBOARD_PASTE) ?
3913                         theClipboard().getAsText() :
3914                         theSelection().get();
3915                 if (clip.empty())
3916                         break;
3917                 // pass to InsertPlaintextString, but
3918                 // only if we have multi-cell content
3919                 if (clip.find_first_of(from_ascii("\t\n")) != docstring::npos) {
3920                         cur.recordUndoInset(INSERT_UNDO);
3921                         if (insertPlaintextString(cur.bv(), clip, false)) {
3922                                 // content has been replaced,
3923                                 // so cursor might be invalid
3924                                 cur.pos() = cur.lastpos();
3925                                 cur.pit() = cur.lastpit();
3926                                 bvcur.setCursor(cur);
3927                                 break;
3928                         }
3929                 }
3930                 // Let the cell handle normal text
3931                 cell(cur.idx())->dispatch(cur, cmd);
3932                 break;
3933         }
3934
3935         case LFUN_PASTE:
3936                 if (!tabularStackDirty()) {
3937                         if (!cur.selIsMultiCell())
3938                                 cell(cur.idx())->dispatch(cur, cmd);
3939                         break;
3940                 }
3941                 if (theClipboard().isInternal() ||
3942                     (!theClipboard().hasInternal() && theClipboard().hasLyXContents())) {
3943                         cur.recordUndoInset(INSERT_UNDO);
3944                         pasteClipboard(cur);
3945                 }
3946                 break;
3947
3948         case LFUN_FONT_EMPH:
3949         case LFUN_FONT_BOLD:
3950         case LFUN_FONT_BOLDSYMBOL:
3951         case LFUN_FONT_ROMAN:
3952         case LFUN_FONT_NOUN:
3953         case LFUN_FONT_ITAL:
3954         case LFUN_FONT_FRAK:
3955         case LFUN_FONT_TYPEWRITER:
3956         case LFUN_FONT_SANS:
3957         case LFUN_TEXTSTYLE_APPLY:
3958         case LFUN_TEXTSTYLE_UPDATE:
3959         case LFUN_FONT_SIZE:
3960         case LFUN_FONT_UNDERLINE:
3961         case LFUN_FONT_STRIKEOUT:
3962         case LFUN_FONT_UULINE:
3963         case LFUN_FONT_UWAVE:
3964         case LFUN_LANGUAGE:
3965         case LFUN_WORD_CAPITALIZE:
3966         case LFUN_WORD_UPCASE:
3967         case LFUN_WORD_LOWCASE:
3968         case LFUN_CHARS_TRANSPOSE:
3969                 if (cur.selIsMultiCell()) {
3970                         row_type rs, re;
3971                         col_type cs, ce;
3972                         getSelection(cur, rs, re, cs, ce);
3973                         Cursor tmpcur = cur;
3974                         for (row_type i = rs; i <= re; ++i) {
3975                                 for (col_type j = cs; j <= ce; ++j) {
3976                                         // cursor follows cell:
3977                                         tmpcur.idx() = tabular.cellIndex(i, j);
3978                                         // select this cell only:
3979                                         tmpcur.pit() = 0;
3980                                         tmpcur.pos() = 0;
3981                                         tmpcur.resetAnchor();
3982                                         tmpcur.pit() = tmpcur.lastpit();
3983                                         tmpcur.pos() = tmpcur.top().lastpos();
3984                                         tmpcur.setCursor(tmpcur);
3985                                         tmpcur.setSelection();
3986                                         cell(tmpcur.idx())->dispatch(tmpcur, cmd);
3987                                 }
3988                         }
3989                         break;
3990                 } else {
3991                         cell(cur.idx())->dispatch(cur, cmd);
3992                         break;
3993                 }
3994
3995         case LFUN_INSET_SETTINGS:
3996                 // relay this lfun to Inset, not to the cell.
3997                 Inset::doDispatch(cur, cmd);
3998                 break;
3999
4000         default:
4001                 // we try to handle this event in the insets dispatch function.
4002                 cell(cur.idx())->dispatch(cur, cmd);
4003                 break;
4004         }
4005 }
4006
4007
4008 // function sets an object as defined in func_status.h:
4009 // states OK, Unknown, Disabled, On, Off.
4010 bool InsetTabular::getStatus(Cursor & cur, FuncRequest const & cmd,
4011         FuncStatus & status) const
4012 {
4013         switch (cmd.action) {
4014         case LFUN_INSET_MODIFY: {
4015                 istringstream is(to_utf8(cmd.argument()));
4016                 string s;
4017                 is >> s;
4018                 if (insetCode(s) != TABULAR_CODE) {
4019                         status.clear();
4020                         status.setEnabled(false);
4021                         break;
4022                 }
4023                 is >> s;
4024                 // FIXME: We only check for the very first argument...
4025                 int action = Tabular::LAST_ACTION;
4026                 int i = 0;
4027                 for (; tabularFeature[i].action != Tabular::LAST_ACTION; ++i) {
4028                         string const tmp = tabularFeature[i].feature;
4029                         if (tmp == s.substr(0, tmp.length())) {
4030                                 action = tabularFeature[i].action;
4031                                 break;
4032                         }
4033                 }
4034                 if (action == Tabular::LAST_ACTION) {
4035                         status.clear();
4036                         status.unknown(true);
4037                         return true;
4038                 }
4039
4040                 string const argument
4041                         = ltrim(s.substr(tabularFeature[i].feature.length()));
4042
4043                 row_type sel_row_start = 0;
4044                 row_type sel_row_end = 0;
4045                 col_type sel_col_start = 0;
4046                 col_type sel_col_end = 0;
4047                 Tabular::ltType dummyltt;
4048                 bool flag = true;
4049
4050                 getSelection(cur, sel_row_start, sel_row_end, sel_col_start, sel_col_end);
4051
4052                 switch (action) {
4053                 case Tabular::SET_PWIDTH:
4054                 case Tabular::SET_MPWIDTH:
4055                 case Tabular::SET_SPECIAL_COLUMN:
4056                 case Tabular::SET_SPECIAL_MULTICOLUMN:
4057                 case Tabular::SET_SPECIAL_MULTIROW:
4058                 case Tabular::APPEND_ROW:
4059                 case Tabular::APPEND_COLUMN:
4060                 case Tabular::DELETE_ROW:
4061                 case Tabular::DELETE_COLUMN:
4062                 case Tabular::COPY_ROW:
4063                 case Tabular::COPY_COLUMN:
4064                 case Tabular::SET_TOP_SPACE:
4065                 case Tabular::SET_BOTTOM_SPACE:
4066                 case Tabular::SET_INTERLINE_SPACE:
4067                         status.clear();
4068                         return true;
4069
4070                 case Tabular::MULTICOLUMN:
4071                         // If a row is set as longtable caption, it must not be allowed
4072                         // to unset that this row is a multicolumn.
4073                         status.setEnabled(sel_row_start == sel_row_end
4074                                 && !tabular.ltCaption(tabular.cellRow(cur.idx())));
4075                         status.setOnOff(tabular.isMultiColumn(cur.idx()));
4076                         break;
4077
4078                 case Tabular::MULTIROW:
4079                         // If a row is set as longtable caption, it must not be allowed
4080                         // to unset that this row is a multirow.
4081                         status.setEnabled(sel_col_start == sel_col_end
4082                                 && !tabular.ltCaption(tabular.cellRow(cur.idx())));
4083                         status.setOnOff(tabular.isMultiRow(cur.idx()));
4084                         break;
4085
4086                 case Tabular::SET_ALL_LINES:
4087                 case Tabular::UNSET_ALL_LINES:
4088                 case Tabular::SET_BORDER_LINES:
4089                         status.setEnabled(!tabular.ltCaption(tabular.cellRow(cur.idx())));
4090                         break;
4091
4092                 case Tabular::SET_LINE_TOP:
4093                 case Tabular::SET_LINE_BOTTOM:
4094                 case Tabular::SET_LINE_LEFT:
4095                 case Tabular::SET_LINE_RIGHT:
4096                         status.setEnabled(!tabular.ltCaption(tabular.cellRow(cur.idx())));
4097                         break;
4098
4099                 case Tabular::TOGGLE_LINE_TOP:
4100                         status.setEnabled(!tabular.ltCaption(tabular.cellRow(cur.idx())));
4101                         status.setOnOff(tabular.topLine(cur.idx()));
4102                         break;
4103
4104                 case Tabular::TOGGLE_LINE_BOTTOM:
4105                         status.setEnabled(!tabular.ltCaption(tabular.cellRow(cur.idx())));
4106                         status.setOnOff(tabular.bottomLine(cur.idx()));
4107                         break;
4108
4109                 case Tabular::TOGGLE_LINE_LEFT:
4110                         status.setEnabled(!tabular.ltCaption(tabular.cellRow(cur.idx())));
4111                         status.setOnOff(tabular.leftLine(cur.idx()));
4112                         break;
4113
4114                 case Tabular::TOGGLE_LINE_RIGHT:
4115                         status.setEnabled(!tabular.ltCaption(tabular.cellRow(cur.idx())));
4116                         status.setOnOff(tabular.rightLine(cur.idx()));
4117                         break;
4118
4119                 case Tabular::M_ALIGN_LEFT:
4120                         flag = false;
4121                 case Tabular::ALIGN_LEFT:
4122                         status.setOnOff(tabular.getAlignment(cur.idx(), flag) == LYX_ALIGN_LEFT);
4123                         break;
4124
4125                 case Tabular::M_ALIGN_RIGHT:
4126                         flag = false;
4127                 case Tabular::ALIGN_RIGHT:
4128                         status.setOnOff(tabular.getAlignment(cur.idx(), flag) == LYX_ALIGN_RIGHT);
4129                         break;
4130
4131                 case Tabular::M_ALIGN_CENTER:
4132                         flag = false;
4133                 case Tabular::ALIGN_CENTER:
4134                         status.setOnOff(tabular.getAlignment(cur.idx(), flag) == LYX_ALIGN_CENTER);
4135                         break;
4136
4137                 case Tabular::ALIGN_BLOCK:
4138                         status.setEnabled(!tabular.getPWidth(cur.idx()).zero());
4139                         status.setOnOff(tabular.getAlignment(cur.idx(), flag) == LYX_ALIGN_BLOCK);
4140                         break;
4141
4142                 case Tabular::M_VALIGN_TOP:
4143                         flag = false;
4144                 case Tabular::VALIGN_TOP:
4145                         status.setEnabled(!tabular.getPWidth(cur.idx()).zero());
4146                         status.setOnOff(
4147                                 tabular.getVAlignment(cur.idx(), flag) == Tabular::LYX_VALIGN_TOP);
4148                         break;
4149
4150                 case Tabular::M_VALIGN_BOTTOM:
4151                         flag = false;
4152                 case Tabular::VALIGN_BOTTOM:
4153                         status.setEnabled(!tabular.getPWidth(cur.idx()).zero());
4154                         status.setOnOff(
4155                                 tabular.getVAlignment(cur.idx(), flag) == Tabular::LYX_VALIGN_BOTTOM);
4156                         break;
4157
4158                 case Tabular::M_VALIGN_MIDDLE:
4159                         flag = false;
4160                 case Tabular::VALIGN_MIDDLE:
4161                         status.setEnabled(!tabular.getPWidth(cur.idx()).zero());
4162                         status.setOnOff(
4163                                 tabular.getVAlignment(cur.idx(), flag) == Tabular::LYX_VALIGN_MIDDLE);
4164                         break;
4165
4166                 case Tabular::SET_LONGTABULAR:
4167                         status.setOnOff(tabular.is_long_tabular);
4168                         break;
4169
4170                 case Tabular::UNSET_LONGTABULAR:
4171                         status.setOnOff(!tabular.is_long_tabular);
4172                         break;
4173
4174                 case Tabular::TOGGLE_ROTATE_TABULAR:
4175                 case Tabular::SET_ROTATE_TABULAR:
4176                         status.setOnOff(tabular.rotate);
4177                         break;
4178
4179                 case Tabular::TABULAR_VALIGN_TOP:
4180                         status.setOnOff(tabular.tabular_valignment 
4181                                 == Tabular::LYX_VALIGN_TOP);
4182                         break;
4183                 case Tabular::TABULAR_VALIGN_MIDDLE:
4184                         status.setOnOff(tabular.tabular_valignment 
4185                                 == Tabular::LYX_VALIGN_MIDDLE);
4186                         break;
4187                 case Tabular::TABULAR_VALIGN_BOTTOM:
4188                         status.setOnOff(tabular.tabular_valignment 
4189                                 == Tabular::LYX_VALIGN_BOTTOM);
4190                         break;
4191
4192                 case Tabular::LONGTABULAR_ALIGN_LEFT:
4193                         status.setOnOff(tabular.longtabular_alignment 
4194                                 == Tabular::LYX_LONGTABULAR_ALIGN_LEFT);
4195                         break;
4196                 case Tabular::LONGTABULAR_ALIGN_CENTER:
4197                         status.setOnOff(tabular.longtabular_alignment 
4198                                 == Tabular::LYX_LONGTABULAR_ALIGN_CENTER);
4199                         break;
4200                 case Tabular::LONGTABULAR_ALIGN_RIGHT:
4201                         status.setOnOff(tabular.longtabular_alignment 
4202                                 == Tabular::LYX_LONGTABULAR_ALIGN_RIGHT);
4203                         break;
4204
4205                 case Tabular::UNSET_ROTATE_TABULAR:
4206                         status.setOnOff(!tabular.rotate);
4207                         break;
4208
4209                 case Tabular::TOGGLE_ROTATE_CELL:
4210                 case Tabular::SET_ROTATE_CELL:
4211                         status.setOnOff(!oneCellHasRotationState(false,
4212                                 sel_row_start, sel_row_end, sel_col_start, sel_col_end));
4213                         break;
4214
4215                 case Tabular::UNSET_ROTATE_CELL:
4216                         status.setOnOff(!oneCellHasRotationState(true,
4217                                 sel_row_start, sel_row_end, sel_col_start, sel_col_end));
4218                         break;
4219
4220                 case Tabular::SET_USEBOX:
4221                         status.setOnOff(convert<int>(argument) == tabular.getUsebox(cur.idx()));
4222                         break;
4223
4224                 // every row can only be one thing:
4225                 // either a footer or header or caption
4226                 case Tabular::SET_LTFIRSTHEAD:
4227                         status.setEnabled(sel_row_start == sel_row_end
4228                                 && !tabular.ltCaption(sel_row_start));
4229                         status.setOnOff(tabular.getRowOfLTFirstHead(sel_row_start, dummyltt));
4230                         break;
4231
4232                 case Tabular::UNSET_LTFIRSTHEAD:
4233                         status.setOnOff(!tabular.getRowOfLTFirstHead(sel_row_start, dummyltt));
4234                         break;
4235
4236                 case Tabular::SET_LTHEAD:
4237                         status.setEnabled(sel_row_start == sel_row_end
4238                                 && !tabular.ltCaption(sel_row_start));
4239                         status.setOnOff(tabular.getRowOfLTHead(sel_row_start, dummyltt));
4240                         break;
4241
4242                 case Tabular::UNSET_LTHEAD:
4243                         status.setOnOff(!tabular.getRowOfLTHead(sel_row_start, dummyltt));
4244                         break;
4245
4246                 case Tabular::SET_LTFOOT:
4247                         status.setEnabled(sel_row_start == sel_row_end
4248                                 && !tabular.ltCaption(sel_row_start));
4249                         status.setOnOff(tabular.getRowOfLTFoot(sel_row_start, dummyltt));
4250                         break;
4251
4252                 case Tabular::UNSET_LTFOOT:
4253                         status.setOnOff(!tabular.getRowOfLTFoot(sel_row_start, dummyltt));
4254                         break;
4255
4256                 case Tabular::SET_LTLASTFOOT:
4257                         status.setEnabled(sel_row_start == sel_row_end
4258                                 && !tabular.ltCaption(sel_row_start));
4259                         status.setOnOff(tabular.getRowOfLTLastFoot(sel_row_start, dummyltt));
4260                         break;
4261
4262                 case Tabular::UNSET_LTLASTFOOT:
4263                         status.setOnOff(!tabular.getRowOfLTLastFoot(sel_row_start, dummyltt));
4264                         break;
4265
4266                 case Tabular::SET_LTNEWPAGE:
4267                         status.setOnOff(tabular.getLTNewPage(sel_row_start));
4268                         break;
4269
4270                 // only one row can be the caption
4271                 // and a multirow cannot be set as caption
4272                 case Tabular::TOGGLE_LTCAPTION:
4273                         status.setEnabled(sel_row_start == sel_row_end
4274                                 && !tabular.getRowOfLTFirstHead(sel_row_start, dummyltt)
4275                                 && !tabular.getRowOfLTHead(sel_row_start, dummyltt)
4276                                 && !tabular.getRowOfLTFoot(sel_row_start, dummyltt)
4277                                 && !tabular.getRowOfLTLastFoot(sel_row_start, dummyltt)
4278                                 && (!tabular.haveLTCaption()
4279                                         || tabular.ltCaption(sel_row_start))
4280                                 && !tabular.isMultiRow(sel_row_start));
4281                         status.setOnOff(tabular.ltCaption(sel_row_start));
4282                         break;
4283
4284                 case Tabular::SET_BOOKTABS:
4285                         status.setOnOff(tabular.use_booktabs);
4286                         break;
4287
4288                 case Tabular::UNSET_BOOKTABS:
4289                         status.setOnOff(!tabular.use_booktabs);
4290                         break;
4291
4292                 default:
4293                         status.clear();
4294                         status.setEnabled(false);
4295                         break;
4296                 }
4297                 return true;
4298         }
4299
4300         // These are only enabled inside tabular
4301         case LFUN_CELL_BACKWARD:
4302         case LFUN_CELL_FORWARD:
4303                 status.setEnabled(true);
4304                 return true;
4305
4306         // disable these with multiple cells selected
4307         case LFUN_INSET_INSERT:
4308         case LFUN_TABULAR_INSERT:
4309         case LFUN_FLEX_INSERT:
4310         case LFUN_FLOAT_INSERT:
4311         case LFUN_FLOAT_WIDE_INSERT:
4312         case LFUN_FOOTNOTE_INSERT:
4313         case LFUN_MARGINALNOTE_INSERT:
4314         case LFUN_MATH_INSERT:
4315         case LFUN_MATH_MODE:
4316         case LFUN_MATH_MUTATE:
4317         case LFUN_MATH_DISPLAY:
4318         case LFUN_NOTE_INSERT:
4319         case LFUN_OPTIONAL_INSERT:
4320         case LFUN_BOX_INSERT:
4321         case LFUN_BRANCH_INSERT:
4322         case LFUN_PHANTOM_INSERT:
4323         case LFUN_WRAP_INSERT:
4324         case LFUN_ERT_INSERT: {
4325                 if (cur.selIsMultiCell()) {
4326                         status.setEnabled(false);
4327                         return true;
4328                 } else
4329                         return cell(cur.idx())->getStatus(cur, cmd, status);
4330         }
4331
4332         // disable in non-fixed-width cells
4333         case LFUN_NEWLINE_INSERT:
4334         case LFUN_BREAK_PARAGRAPH: {
4335                 if (tabular.getPWidth(cur.idx()).zero()) {
4336                         status.setEnabled(false);
4337                         return true;
4338                 } else
4339                         return cell(cur.idx())->getStatus(cur, cmd, status);
4340         }
4341
4342         case LFUN_NEWPAGE_INSERT:
4343                 status.setEnabled(false);
4344                 return true;
4345
4346         case LFUN_PASTE:
4347                 if (tabularStackDirty() && theClipboard().isInternal()) {
4348                         if (cur.selIsMultiCell()) {
4349                                 row_type rs, re;
4350                                 col_type cs, ce;
4351                                 getSelection(cur, rs, re, cs, ce);
4352                                 if (paste_tabular && paste_tabular->column_info.size() == ce - cs + 1
4353                                           && paste_tabular->row_info.size() == re - rs + 1)
4354                                         status.setEnabled(true);        
4355                                 else {
4356                                         status.setEnabled(false);
4357                                         status.message(_("Selection size should match clipboard content."));
4358                                 }
4359                         } else
4360                                 status.setEnabled(true);
4361                         return true;
4362                 }
4363                 return cell(cur.idx())->getStatus(cur, cmd, status);
4364
4365         case LFUN_INSET_SETTINGS:
4366                 // relay this lfun to Inset, not to the cell.
4367                 return Inset::getStatus(cur, cmd, status);
4368
4369         default:
4370                 // we try to handle this event in the insets dispatch function.
4371                 return cell(cur.idx())->getStatus(cur, cmd, status);
4372         }
4373         return false;
4374 }
4375
4376
4377 Inset::DisplayType InsetTabular::display() const
4378 {
4379                 if (tabular.is_long_tabular) {
4380                         switch (tabular.longtabular_alignment) {
4381                         case Tabular::LYX_LONGTABULAR_ALIGN_LEFT:
4382                                 return AlignLeft;
4383                         case Tabular::LYX_LONGTABULAR_ALIGN_CENTER:
4384                                 return AlignCenter;
4385                         case Tabular::LYX_LONGTABULAR_ALIGN_RIGHT:
4386                                 return AlignRight;
4387                         default:
4388                                 return AlignCenter;
4389                         }
4390                 } else
4391                         return Inline;
4392 }
4393
4394
4395 int InsetTabular::latex(odocstream & os, OutputParams const & runparams) const
4396 {
4397         return tabular.latex(os, runparams);
4398 }
4399
4400
4401 int InsetTabular::plaintext(odocstream & os, OutputParams const & runparams) const
4402 {
4403         os << '\n'; // output table on a new line
4404         int const dp = runparams.linelen > 0 ? runparams.depth : 0;
4405         tabular.plaintext(os, runparams, dp, false, 0);
4406         return PLAINTEXT_NEWLINE;
4407 }
4408
4409
4410 int InsetTabular::docbook(odocstream & os, OutputParams const & runparams) const
4411 {
4412         int ret = 0;
4413         Inset * master = 0;
4414
4415         // FIXME: Why not pass a proper DocIterator here?
4416 #if 0
4417         // if the table is inside a float it doesn't need the informaltable
4418         // wrapper. Search for it.
4419         for (master = owner(); master; master = master->owner())
4420                 if (master->lyxCode() == FLOAT_CODE)
4421                         break;
4422 #endif
4423
4424         if (!master) {
4425                 os << "<informaltable>";
4426                 ++ret;
4427         }
4428         ret += tabular.docbook(os, runparams);
4429         if (!master) {
4430                 os << "</informaltable>";
4431                 ++ret;
4432         }
4433         return ret;
4434 }
4435
4436
4437 docstring InsetTabular::xhtml(XHTMLStream & xs, OutputParams const & rp) const
4438 {
4439         // FIXME XHTML
4440         // It'd be better to be able to get this from an InsetLayout, but at present
4441         // InsetLayouts do not seem really to work for things that aren't InsetTexts.
4442         xs << html::StartTag("table");
4443         docstring ret = tabular.xhtml(xs, rp);
4444         xs << html::EndTag("table");
4445         return ret;
4446 }
4447
4448
4449 void InsetTabular::validate(LaTeXFeatures & features) const
4450 {
4451         tabular.validate(features);
4452         // FIXME XHTML
4453         // It'd be better to be able to get this from an InsetLayout, but at present
4454         // InsetLayouts do not seem really to work for things that aren't InsetTexts.
4455         if (features.runparams().flavor == OutputParams::HTML)
4456                 features.addPreambleSnippet("<style type=\"text/css\">\n"
4457       "table { border: 1px solid black; display: inline-block; }\n"
4458       "td { border: 1px solid black; padding: 0.5ex; }\n"
4459       "</style>");
4460 }
4461
4462
4463 shared_ptr<InsetTableCell const> InsetTabular::cell(idx_type idx) const
4464 {
4465         return tabular.cellInset(idx);
4466 }
4467
4468
4469 shared_ptr<InsetTableCell> InsetTabular::cell(idx_type idx)
4470 {
4471         return tabular.cellInset(idx);
4472 }
4473
4474
4475 void InsetTabular::cursorPos(BufferView const & bv,
4476                 CursorSlice const & sl, bool boundary, int & x, int & y) const
4477 {
4478         cell(sl.idx())->cursorPos(bv, sl, boundary, x, y);
4479
4480         int const row = tabular.cellRow(sl.idx());
4481         int const col = tabular.cellColumn(sl.idx());
4482
4483         // y offset     correction
4484         for (int i = 0; i <= row; ++i) {
4485                 if (tabular.isPartOfMultiRow(i, col))
4486                         continue;
4487                 if (i != 0) {
4488                         y += tabular.rowAscent(i);
4489                         y += tabular.interRowSpace(i);
4490                 }
4491                 if (i != row)
4492                         y += tabular.rowDescent(i);
4493         }
4494         y += tabular.textVOffset(sl.idx());
4495
4496         // x offset correction
4497         for (int c = 0; c < col; ++c)
4498                 x += tabular.column_info[c].width;
4499         
4500         x += tabular.textHOffset(sl.idx());
4501         x += ADD_TO_TABULAR_WIDTH;
4502         x += scx_;
4503 }
4504
4505
4506 int InsetTabular::dist(BufferView & bv, idx_type const cell, int x, int y) const
4507 {
4508         int xx = 0;
4509         int yy = 0;
4510         Inset const & inset = *tabular.cellInset(cell);
4511         Point o = bv.coordCache().getInsets().xy(&inset);
4512         int const xbeg = o.x_ - tabular.textHOffset(cell);
4513         int const xend = xbeg + tabular.columnWidth(cell);
4514         row_type const row = tabular.cellRow(cell);
4515         int const ybeg = o.y_ - tabular.rowAscent(row)
4516                 - tabular.interRowSpace(row);
4517         int const yend = o.y_ + tabular.rowDescent(row);
4518
4519         if (x < xbeg)
4520                 xx = xbeg - x;
4521         else if (x > xend)
4522                 xx = x - xend;
4523
4524         if (y < ybeg)
4525                 yy = ybeg - y;
4526         else if (y > yend)
4527                 yy = y - yend;
4528
4529         //lyxerr << " xbeg=" << xbeg << "  xend=" << xend
4530         //       << " ybeg=" << ybeg << " yend=" << yend
4531         //       << " xx=" << xx << " yy=" << yy
4532         //       << " dist=" << xx + yy << endl;
4533         return xx + yy;
4534 }
4535
4536
4537 Inset * InsetTabular::editXY(Cursor & cur, int x, int y)
4538 {
4539         //lyxerr << "InsetTabular::editXY: " << this << endl;
4540         cur.setSelection(false);
4541         cur.push(*this);
4542         cur.idx() = getNearestCell(cur.bv(), x, y);
4543         resetPos(cur);
4544         return cur.bv().textMetrics(&cell(cur.idx())->text()).editXY(cur, x, y);
4545 }
4546
4547
4548 void InsetTabular::setCursorFromCoordinates(Cursor & cur, int x, int y) const
4549 {
4550         cur.idx() = getNearestCell(cur.bv(), x, y);
4551         cur.bv().textMetrics(&cell(cur.idx())->text()).setCursorFromCoordinates(cur, x, y);
4552 }
4553
4554
4555 InsetTabular::idx_type InsetTabular::getNearestCell(BufferView & bv, int x, int y) const
4556 {
4557         idx_type idx_min = 0;
4558         int dist_min = numeric_limits<int>::max();
4559         for (idx_type i = 0, n = nargs(); i != n; ++i) {
4560                 if (bv.coordCache().getInsets().has(tabular.cellInset(i).get())) {
4561                         int const d = dist(bv, i, x, y);
4562                         if (d < dist_min) {
4563                                 dist_min = d;
4564                                 idx_min = i;
4565                         }
4566                 }
4567         }
4568         return idx_min;
4569 }
4570
4571
4572 int InsetTabular::cellXPos(idx_type const cell) const
4573 {
4574         col_type col = tabular.cellColumn(cell);
4575         int lx = 0;
4576         for (col_type c = 0; c < col; ++c)
4577                 lx += tabular.columnWidth(c);
4578
4579         return lx;
4580 }
4581
4582
4583 void InsetTabular::resetPos(Cursor & cur) const
4584 {
4585         BufferView & bv = cur.bv();
4586         int const maxwidth = bv.workWidth();
4587
4588         int const scx_old = scx_;
4589         int const i = cur.find(this);
4590         if (i == -1) {
4591                 scx_ = 0;
4592         } else {
4593                 int const X1 = 0;
4594                 int const X2 = maxwidth;
4595                 int const offset = ADD_TO_TABULAR_WIDTH + 2;
4596                 int const x1 = xo(cur.bv()) + cellXPos(cur[i].idx()) + offset;
4597                 int const x2 = x1 + tabular.columnWidth(cur[i].idx());
4598
4599                 if (x1 < X1)
4600                         scx_ = X1 + 20 - x1;
4601                 else if (x2 > X2)
4602                         scx_ = X2 - 20 - x2;
4603                 else
4604                         scx_ = 0;
4605         }
4606
4607         // only update if offset changed
4608         if (scx_ != scx_old)
4609                 cur.updateFlags(Update::Force | Update::FitCursor);
4610 }
4611
4612
4613 void InsetTabular::moveNextCell(Cursor & cur, EntryDirection entry_from)
4614 {
4615         row_type const row = tabular.cellRow(cur.idx());
4616         col_type const col = tabular.cellColumn(cur.idx());
4617
4618         if (isRightToLeft(cur)) {
4619                 if (tabular.cellColumn(cur.idx()) == 0) {
4620                         if (row == tabular.row_info.size() - 1)
4621                                 return;
4622                         cur.idx() = tabular.cellBelow(tabular.getLastCellInRow(row));
4623                 } else {
4624                         if (cur.idx() == 0)
4625                                 return;
4626                         if (col == 0)
4627                                 cur.idx() = tabular.getLastCellInRow(row - 1);
4628                         else
4629                                 cur.idx() = tabular.cellIndex(row, col - 1);
4630                 }
4631         } else {
4632                 if (tabular.isLastCell(cur.idx()))
4633                         return;
4634                 if (cur.idx() == tabular.getLastCellInRow(row))
4635                         cur.idx() = tabular.cellIndex(row + 1, 0);
4636                 else
4637                         cur.idx() = tabular.cellIndex(row, col + 1);
4638         }
4639
4640         cur.boundary(false);
4641
4642         if (cur.selIsMultiCell()) {
4643                 cur.pit() = cur.lastpit();
4644                 cur.pos() = cur.lastpos();
4645                 resetPos(cur);
4646                 return;
4647         }
4648
4649         cur.pit() = 0;
4650         cur.pos() = 0;
4651
4652         // in visual mode, place cursor at extreme left or right
4653         
4654         switch(entry_from) {
4655
4656         case ENTRY_DIRECTION_RIGHT:
4657                 cur.posVisToRowExtremity(false /* !left */);
4658                 break;
4659         case ENTRY_DIRECTION_LEFT:
4660                 cur.posVisToRowExtremity(true /* left */);
4661                 break;
4662         case ENTRY_DIRECTION_IGNORE:
4663                 // nothing to do in this case
4664                 break;
4665
4666         }
4667         cur.setCurrentFont();
4668         resetPos(cur);
4669 }
4670
4671
4672 void InsetTabular::movePrevCell(Cursor & cur, EntryDirection entry_from)
4673 {
4674         row_type const row = tabular.cellRow(cur.idx());
4675         col_type const col = tabular.cellColumn(cur.idx());
4676
4677         if (isRightToLeft(cur)) {
4678                 if (cur.idx() == tabular.getLastCellInRow(row)) {
4679                         if (row == 0)
4680                                 return;
4681                         cur.idx() = tabular.getFirstCellInRow(row);
4682                         cur.idx() = tabular.cellAbove(cur.idx());
4683                 } else {
4684                         if (tabular.isLastCell(cur.idx()))
4685                                 return;
4686                         if (cur.idx() == tabular.getLastCellInRow(row))
4687                                 cur.idx() = tabular.cellIndex(row + 1, 0);
4688                         else
4689                                 cur.idx() = tabular.cellIndex(row, col + 1);
4690                 }
4691         } else {
4692                 if (cur.idx() == 0) // first cell
4693                         return;
4694                 if (col == 0)
4695                         cur.idx() = tabular.getLastCellInRow(row - 1);
4696                 else
4697                         cur.idx() = tabular.cellIndex(row, col - 1);
4698         }
4699
4700         if (cur.selIsMultiCell()) {
4701                 cur.pit() = cur.lastpit();
4702                 cur.pos() = cur.lastpos();
4703                 resetPos(cur);
4704                 return;
4705         }
4706
4707         cur.pit() = cur.lastpit();
4708         cur.pos() = cur.lastpos();
4709
4710         // in visual mode, place cursor at extreme left or right
4711         
4712         switch(entry_from) {
4713
4714         case ENTRY_DIRECTION_RIGHT:
4715                 cur.posVisToRowExtremity(false /* !left */);
4716                 break;
4717         case ENTRY_DIRECTION_LEFT:
4718                 cur.posVisToRowExtremity(true /* left */);
4719                 break;
4720         case ENTRY_DIRECTION_IGNORE:
4721                 // nothing to do in this case
4722                 break;
4723
4724         }
4725         cur.setCurrentFont();
4726         resetPos(cur);
4727 }
4728
4729
4730 bool InsetTabular::tabularFeatures(Cursor & cur, string const & argument)
4731 {
4732         istringstream is(argument);
4733         string s;
4734         is >> s;
4735         if (insetCode(s) != TABULAR_CODE)
4736                 return false;
4737
4738         // Safe guard.
4739         size_t safe_guard = 0;
4740         for (;;) {
4741                 if (is.eof())
4742                         break;
4743                 safe_guard++;
4744                 if (safe_guard > 1000) {
4745                         LYXERR0("parameter max count reached!");
4746                         break;
4747                 }
4748                 is >> s;
4749                 Tabular::Feature action = Tabular::LAST_ACTION;
4750
4751                 size_t i = 0;
4752                 for (; tabularFeature[i].action != Tabular::LAST_ACTION; ++i) {
4753                         if (s != tabularFeature[i].feature)
4754                                 continue;
4755
4756                         action = tabularFeature[i].action;
4757                         break;
4758                 }
4759                 if (action == Tabular::LAST_ACTION) {
4760                         LYXERR0("Feature not found " << s);
4761                         continue;
4762                 }
4763                 string val;
4764                 if (tabularFeature[i].need_value)
4765                         is >> val;
4766                 LYXERR(Debug::DEBUG, "Feature: " << s << "\t\tvalue: " << val);
4767                 tabularFeatures(cur, action, val);
4768         }
4769         return true;
4770 }
4771
4772
4773 static void checkLongtableSpecial(Tabular::ltType & ltt,
4774                           string const & special, bool & flag)
4775 {
4776         if (special == "dl_above") {
4777                 ltt.topDL = flag;
4778                 ltt.set = false;
4779         } else if (special == "dl_below") {
4780                 ltt.bottomDL = flag;
4781                 ltt.set = false;
4782         } else if (special == "empty") {
4783                 ltt.empty = flag;
4784                 ltt.set = false;
4785         } else if (flag) {
4786                 ltt.empty = false;
4787                 ltt.set = true;
4788         }
4789 }
4790
4791 bool InsetTabular::oneCellHasRotationState(bool rotated,
4792                 row_type row_start, row_type row_end,
4793                 col_type col_start, col_type col_end) const {
4794
4795         for (row_type i = row_start; i <= row_end; ++i) {
4796                 for (col_type j = col_start; j <= col_end; ++j) {
4797                         if (tabular.getRotateCell(tabular.cellIndex(i, j))
4798                                 == rotated) {
4799                                 return true;
4800                         }
4801                 }
4802         }
4803         return false;
4804 }
4805
4806 void InsetTabular::tabularFeatures(Cursor & cur,
4807         Tabular::Feature feature, string const & value)
4808 {
4809         col_type sel_col_start;
4810         col_type sel_col_end;
4811         row_type sel_row_start;
4812         row_type sel_row_end;
4813         bool setLines = false;
4814         LyXAlignment setAlign = LYX_ALIGN_LEFT;
4815         Tabular::VAlignment setVAlign = Tabular::LYX_VALIGN_TOP;
4816
4817         switch (feature) {
4818
4819         case Tabular::M_ALIGN_LEFT:
4820         case Tabular::ALIGN_LEFT:
4821                 setAlign = LYX_ALIGN_LEFT;
4822                 break;
4823
4824         case Tabular::M_ALIGN_RIGHT:
4825         case Tabular::ALIGN_RIGHT:
4826                 setAlign = LYX_ALIGN_RIGHT;
4827                 break;
4828
4829         case Tabular::M_ALIGN_CENTER:
4830         case Tabular::ALIGN_CENTER:
4831                 setAlign = LYX_ALIGN_CENTER;
4832                 break;
4833
4834         case Tabular::ALIGN_BLOCK:
4835                 setAlign = LYX_ALIGN_BLOCK;
4836                 break;
4837
4838         case Tabular::M_VALIGN_TOP:
4839         case Tabular::VALIGN_TOP:
4840                 setVAlign = Tabular::LYX_VALIGN_TOP;
4841                 break;
4842
4843         case Tabular::M_VALIGN_BOTTOM:
4844         case Tabular::VALIGN_BOTTOM:
4845                 setVAlign = Tabular::LYX_VALIGN_BOTTOM;
4846                 break;
4847
4848         case Tabular::M_VALIGN_MIDDLE:
4849         case Tabular::VALIGN_MIDDLE:
4850                 setVAlign = Tabular::LYX_VALIGN_MIDDLE;
4851                 break;
4852
4853         default:
4854                 break;
4855         }
4856
4857         cur.recordUndoInset(ATOMIC_UNDO);
4858
4859         getSelection(cur, sel_row_start, sel_row_end, sel_col_start, sel_col_end);
4860         row_type const row = tabular.cellRow(cur.idx());
4861         col_type const column = tabular.cellColumn(cur.idx());
4862         bool flag = true;
4863         Tabular::ltType ltt;
4864
4865         switch (feature) {
4866
4867         case Tabular::SET_PWIDTH: {
4868                 Length const len(value);
4869                 tabular.setColumnPWidth(cur, cur.idx(), len);
4870                 if (len.zero()
4871                     && tabular.getAlignment(cur.idx(), true) == LYX_ALIGN_BLOCK)
4872                         tabularFeatures(cur, Tabular::ALIGN_CENTER, string());
4873                 break;
4874         }
4875
4876         case Tabular::SET_MPWIDTH:
4877                 tabular.setMColumnPWidth(cur, cur.idx(), Length(value));
4878                 break;
4879
4880         case Tabular::SET_SPECIAL_COLUMN:
4881         case Tabular::SET_SPECIAL_MULTICOLUMN:
4882                 if (value == "none")
4883                         tabular.setAlignSpecial(cur.idx(), docstring(), feature);
4884                 else
4885                         tabular.setAlignSpecial(cur.idx(), from_utf8(value), feature);
4886                 break;
4887
4888         case Tabular::SET_SPECIAL_MULTIROW:
4889                 //FIXME: noting to do here?
4890                 break;
4891
4892         case Tabular::APPEND_ROW:
4893                 // append the row into the tabular
4894                 tabular.appendRow(cur.idx());
4895                 break;
4896
4897         case Tabular::APPEND_COLUMN:
4898                 // append the column into the tabular
4899                 tabular.appendColumn(cur.idx());
4900                 cur.idx() = tabular.cellIndex(row, column);
4901                 break;
4902
4903         case Tabular::DELETE_ROW:
4904                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4905                         tabular.deleteRow(sel_row_start);
4906                 if (sel_row_start >= tabular.row_info.size())
4907                         --sel_row_start;
4908                 cur.idx() = tabular.cellIndex(sel_row_start, column);
4909                 cur.pit() = 0;
4910                 cur.pos() = 0;
4911                 cur.setSelection(false);
4912                 break;
4913
4914         case Tabular::DELETE_COLUMN:
4915                 for (col_type i = sel_col_start; i <= sel_col_end; ++i)
4916                         tabular.deleteColumn(sel_col_start);
4917                 if (sel_col_start >= tabular.column_info.size())
4918                         --sel_col_start;
4919                 cur.idx() = tabular.cellIndex(row, sel_col_start);
4920                 cur.pit() = 0;
4921                 cur.pos() = 0;
4922                 cur.setSelection(false);
4923                 break;
4924
4925         case Tabular::COPY_ROW:
4926                 tabular.copyRow(row);
4927                 break;
4928
4929         case Tabular::COPY_COLUMN:
4930                 tabular.copyColumn(column);
4931                 cur.idx() = tabular.cellIndex(row, column);
4932                 break;
4933
4934         case Tabular::SET_LINE_TOP:
4935         case Tabular::TOGGLE_LINE_TOP: {
4936                 bool lineSet = (feature == Tabular::SET_LINE_TOP)
4937                                ? (value == "true") : !tabular.topLine(cur.idx());
4938                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4939                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
4940                                 tabular.setTopLine(tabular.cellIndex(i, j), lineSet);
4941                 break;
4942         }
4943
4944         case Tabular::SET_LINE_BOTTOM:
4945         case Tabular::TOGGLE_LINE_BOTTOM: {
4946                 bool lineSet = (feature == Tabular::SET_LINE_BOTTOM)
4947                                ? (value == "true") : !tabular.bottomLine(cur.idx());
4948                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4949                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
4950                                 tabular.setBottomLine(tabular.cellIndex(i, j), lineSet);
4951                 break;
4952         }
4953
4954         case Tabular::SET_LINE_LEFT:
4955         case Tabular::TOGGLE_LINE_LEFT: {
4956                 bool lineSet = (feature == Tabular::SET_LINE_LEFT)
4957                                ? (value == "true") : !tabular.leftLine(cur.idx());
4958                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4959                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
4960                                 tabular.setLeftLine(tabular.cellIndex(i, j), lineSet);
4961                 break;
4962         }
4963
4964         case Tabular::SET_LINE_RIGHT:
4965         case Tabular::TOGGLE_LINE_RIGHT: {
4966                 bool lineSet = (feature == Tabular::SET_LINE_RIGHT)
4967                                ? (value == "true") : !tabular.rightLine(cur.idx());
4968                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4969                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
4970                                 tabular.setRightLine(tabular.cellIndex(i, j), lineSet);
4971                 break;
4972         }
4973
4974         case Tabular::M_ALIGN_LEFT:
4975         case Tabular::M_ALIGN_RIGHT:
4976         case Tabular::M_ALIGN_CENTER:
4977                 flag = false;
4978         case Tabular::ALIGN_LEFT:
4979         case Tabular::ALIGN_RIGHT:
4980         case Tabular::ALIGN_CENTER:
4981         case Tabular::ALIGN_BLOCK:
4982                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4983                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
4984                                 tabular.setAlignment(tabular.cellIndex(i, j), setAlign, flag);
4985                 break;
4986
4987         case Tabular::M_VALIGN_TOP:
4988         case Tabular::M_VALIGN_BOTTOM:
4989         case Tabular::M_VALIGN_MIDDLE:
4990                 flag = false;
4991         case Tabular::VALIGN_TOP:
4992         case Tabular::VALIGN_BOTTOM:
4993         case Tabular::VALIGN_MIDDLE:
4994                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4995                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
4996                                 tabular.setVAlignment(tabular.cellIndex(i, j), setVAlign, flag);
4997                 break;
4998
4999         case Tabular::MULTICOLUMN: {
5000                 if (!cur.selection()) {
5001                         // just multicol for one single cell
5002                         // check whether we are completely in a multicol
5003                         if (tabular.isMultiColumn(cur.idx()))
5004                                 tabular.unsetMultiColumn(cur.idx());
5005                         else
5006                                 tabular.setMultiColumn(cur.idx(), 1);
5007                         break;
5008                 }
5009                 // we have a selection so this means we just add all this
5010                 // cells to form a multicolumn cell
5011                 idx_type const s_start = cur.selBegin().idx();
5012                 row_type const col_start = tabular.cellColumn(s_start);
5013                 row_type const col_end = tabular.cellColumn(cur.selEnd().idx());
5014                 tabular.setMultiColumn(s_start, col_end - col_start + 1);
5015                 cur.idx() = s_start;
5016                 cur.pit() = 0;
5017                 cur.pos() = 0;
5018                 cur.setSelection(false);
5019                 break;
5020         }
5021         
5022         case Tabular::MULTIROW: {
5023                 if (!cur.selection()) {
5024                         // just multirow for one single cell
5025                         // check whether we are completely in a multirow
5026                         if (tabular.isMultiRow(cur.idx()))
5027                                 tabular.unsetMultiRow(cur.idx());
5028                         else
5029                                 tabular.setMultiRow(cur.idx(), 1);
5030                         break;
5031                 }
5032                 // we have a selection so this means we just add all this
5033                 // cells to form a multirow cell
5034                 idx_type const s_start = cur.selBegin().idx();
5035                 row_type const row_start = tabular.cellRow(s_start);
5036                 row_type const row_end = tabular.cellRow(cur.selEnd().idx());
5037                 tabular.setMultiRow(s_start, row_end - row_start + 1);
5038                 cur.idx() = s_start;
5039                 cur.pit() = 0;
5040                 cur.pos() = 0;
5041                 cur.setSelection(false);
5042                 break;
5043         }
5044
5045         case Tabular::SET_ALL_LINES:
5046                 setLines = true;
5047         case Tabular::UNSET_ALL_LINES:
5048                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
5049                         for (col_type j = sel_col_start; j <= sel_col_end; ++j) {
5050                                 idx_type const cell = tabular.cellIndex(i,j);
5051                                 tabular.setTopLine(cell, setLines);
5052                                 tabular.setBottomLine(cell, setLines);
5053                                 tabular.setRightLine(cell, setLines);
5054                                 tabular.setLeftLine(cell, setLines);
5055                         }
5056                 break;
5057
5058         case Tabular::SET_BORDER_LINES:
5059                 for (row_type i = sel_row_start; i <= sel_row_end; ++i) {
5060                         tabular.setLeftLine(tabular.cellIndex(i, sel_col_start), true);
5061                         tabular.setRightLine(tabular.cellIndex(i, sel_col_end), true);
5062                 }
5063                 for (col_type j = sel_col_start; j <= sel_col_end; ++j) {
5064                         tabular.setTopLine(tabular.cellIndex(sel_row_start, j), true);
5065                         tabular.setBottomLine(tabular.cellIndex(sel_row_end, j), true);
5066                 }
5067                 break;
5068
5069         case Tabular::SET_LONGTABULAR:
5070                 tabular.is_long_tabular = true;
5071                 break;
5072
5073         case Tabular::UNSET_LONGTABULAR:
5074                 for (row_type i = 0; i < tabular.row_info.size(); ++i) {
5075                         if (tabular.ltCaption(i)) {
5076                                 cur.idx() = tabular.cellIndex(i, 0);
5077                                 cur.pit() = 0;
5078                                 cur.pos() = 0;
5079                                 tabularFeatures(cur, Tabular::TOGGLE_LTCAPTION);
5080                         }
5081                 }
5082                 tabular.is_long_tabular = false;
5083                 break;
5084
5085         case Tabular::SET_ROTATE_TABULAR:
5086                 tabular.rotate = true;
5087                 break;
5088
5089         case Tabular::UNSET_ROTATE_TABULAR:
5090                 tabular.rotate = false;
5091                 break;
5092
5093         case Tabular::TOGGLE_ROTATE_TABULAR:
5094                 tabular.rotate = !tabular.rotate;
5095                 break;
5096
5097         case Tabular::TABULAR_VALIGN_TOP:
5098                 tabular.tabular_valignment = Tabular::LYX_VALIGN_TOP;
5099                 break;
5100
5101         case Tabular::TABULAR_VALIGN_MIDDLE:
5102                 tabular.tabular_valignment = Tabular::LYX_VALIGN_MIDDLE;
5103                 break;
5104
5105         case Tabular::TABULAR_VALIGN_BOTTOM:
5106                 tabular.tabular_valignment = Tabular::LYX_VALIGN_BOTTOM;
5107                 break;
5108
5109         case Tabular::LONGTABULAR_ALIGN_LEFT:
5110                 tabular.longtabular_alignment = Tabular::LYX_LONGTABULAR_ALIGN_LEFT;
5111                 break;
5112
5113         case Tabular::LONGTABULAR_ALIGN_CENTER:
5114                 tabular.longtabular_alignment = Tabular::LYX_LONGTABULAR_ALIGN_CENTER;
5115                 break;
5116
5117         case Tabular::LONGTABULAR_ALIGN_RIGHT:
5118                 tabular.longtabular_alignment = Tabular::LYX_LONGTABULAR_ALIGN_RIGHT;
5119                 break;
5120
5121                 
5122
5123         case Tabular::SET_ROTATE_CELL:
5124                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
5125                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
5126                                 tabular.setRotateCell(
5127                                         tabular.cellIndex(i, j), true);
5128                 break;
5129
5130         case Tabular::UNSET_ROTATE_CELL:
5131                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
5132                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
5133                                 tabular.setRotateCell(tabular.cellIndex(i, j), false);
5134                 break;
5135
5136         case Tabular::TOGGLE_ROTATE_CELL:
5137                 {
5138                 bool oneNotRotated = oneCellHasRotationState(false,
5139                         sel_row_start, sel_row_end, sel_col_start, sel_col_end);
5140
5141                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
5142                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
5143                                 tabular.setRotateCell(tabular.cellIndex(i, j),
5144                                                                           oneNotRotated);
5145                 }
5146                 break;
5147
5148         case Tabular::SET_USEBOX: {
5149                 Tabular::BoxType val = Tabular::BoxType(convert<int>(value));
5150                 if (val == tabular.getUsebox(cur.idx()))
5151                         val = Tabular::BOX_NONE;
5152                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
5153                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
5154                                 tabular.setUsebox(tabular.cellIndex(i, j), val);
5155                 break;
5156         }
5157
5158         case Tabular::UNSET_LTFIRSTHEAD:
5159                 flag = false;
5160         case Tabular::SET_LTFIRSTHEAD:
5161                 tabular.getRowOfLTFirstHead(row, ltt);
5162                 checkLongtableSpecial(ltt, value, flag);
5163                 tabular.setLTHead(row, flag, ltt, true);
5164                 break;
5165
5166         case Tabular::UNSET_LTHEAD:
5167                 flag = false;
5168         case Tabular::SET_LTHEAD:
5169                 tabular.getRowOfLTHead(row, ltt);
5170                 checkLongtableSpecial(ltt, value, flag);
5171                 tabular.setLTHead(row, flag, ltt, false);
5172                 break;
5173
5174         case Tabular::UNSET_LTFOOT:
5175                 flag = false;
5176         case Tabular::SET_LTFOOT:
5177                 tabular.getRowOfLTFoot(row, ltt);
5178                 checkLongtableSpecial(ltt, value, flag);
5179                 tabular.setLTFoot(row, flag, ltt, false);
5180                 break;
5181
5182         case Tabular::UNSET_LTLASTFOOT:
5183                 flag = false;
5184         case Tabular::SET_LTLASTFOOT:
5185                 tabular.getRowOfLTLastFoot(row, ltt);
5186                 checkLongtableSpecial(ltt, value, flag);
5187                 tabular.setLTFoot(row, flag, ltt, true);
5188                 break;
5189
5190         case Tabular::SET_LTNEWPAGE:
5191                 tabular.setLTNewPage(row, !tabular.getLTNewPage(row));
5192                 break;
5193
5194         case Tabular::TOGGLE_LTCAPTION: {
5195                 bool const set = !tabular.ltCaption(row);
5196                 cur.idx() = tabular.setLTCaption(row, set);
5197                 cur.pit() = 0;
5198                 cur.pos() = 0;
5199                 cur.setSelection(false);
5200
5201                 if (set) {
5202                         // When a row is set as caption, then also insert
5203                         // a caption. Otherwise the LaTeX output is broken.
5204                         lyx::dispatch(FuncRequest(LFUN_INSET_SELECT_ALL));
5205                         lyx::dispatch(FuncRequest(LFUN_CAPTION_INSERT));
5206                 } else {
5207                         FuncRequest fr(LFUN_INSET_DISSOLVE, "caption");
5208                         if (lyx::getStatus(fr).enabled())
5209                                 lyx::dispatch(fr);
5210                 }
5211                 break;
5212         }
5213
5214         case Tabular::SET_BOOKTABS:
5215                 tabular.use_booktabs = true;
5216                 break;
5217
5218         case Tabular::UNSET_BOOKTABS:
5219                 tabular.use_booktabs = false;
5220                 break;
5221
5222         case Tabular::SET_TOP_SPACE: {
5223                 Length len;
5224                 if (value == "default")
5225                         for (row_type i = sel_row_start; i <= sel_row_end; ++i)
5226                                 tabular.row_info[i].top_space_default = true;
5227                 else if (value == "none")
5228                         for (row_type i = sel_row_start; i <= sel_row_end; ++i) {
5229                                 tabular.row_info[i].top_space_default = false;
5230                                 tabular.row_info[i].top_space = len;
5231                         }
5232                 else if (isValidLength(value, &len))
5233                         for (row_type i = sel_row_start; i <= sel_row_end; ++i) {
5234                                 tabular.row_info[i].top_space_default = false;
5235                                 tabular.row_info[i].top_space = len;
5236                         }
5237                 break;
5238         }
5239
5240         case Tabular::SET_BOTTOM_SPACE: {
5241                 Length len;
5242                 if (value == "default")
5243                         for (row_type i = sel_row_start; i <= sel_row_end; ++i)
5244                                 tabular.row_info[i].bottom_space_default = true;
5245                 else if (value == "none")
5246                         for (row_type i = sel_row_start; i <= sel_row_end; ++i) {
5247                                 tabular.row_info[i].bottom_space_default = false;
5248                                 tabular.row_info[i].bottom_space = len;
5249                         }
5250                 else if (isValidLength(value, &len))
5251                         for (row_type i = sel_row_start; i <= sel_row_end; ++i) {
5252                                 tabular.row_info[i].bottom_space_default = false;
5253                                 tabular.row_info[i].bottom_space = len;
5254                         }
5255                 break;
5256         }
5257
5258         case Tabular::SET_INTERLINE_SPACE: {
5259                 Length len;
5260                 if (value == "default")
5261                         for (row_type i = sel_row_start; i <= sel_row_end; ++i)
5262                                 tabular.row_info[i].interline_space_default = true;
5263                 else if (value == "none")
5264                         for (row_type i = sel_row_start; i <= sel_row_end; ++i) {
5265                                 tabular.row_info[i].interline_space_default = false;
5266                                 tabular.row_info[i].interline_space = len;
5267                         }
5268                 else if (isValidLength(value, &len))
5269                         for (row_type i = sel_row_start; i <= sel_row_end; ++i) {
5270                                 tabular.row_info[i].interline_space_default = false;
5271                                 tabular.row_info[i].interline_space = len;
5272                         }
5273                 break;
5274         }
5275
5276         // dummy stuff just to avoid warnings
5277         case Tabular::LAST_ACTION:
5278                 break;
5279         }
5280 }
5281
5282
5283 bool InsetTabular::copySelection(Cursor & cur)
5284 {
5285         if (!cur.selection())
5286                 return false;
5287
5288         row_type rs, re;
5289         col_type cs, ce;
5290         getSelection(cur, rs, re, cs, ce);
5291
5292         paste_tabular.reset(new Tabular(tabular));
5293
5294         for (row_type i = 0; i < rs; ++i)
5295                 paste_tabular->deleteRow(0);
5296
5297         row_type const rows = re - rs + 1;
5298         while (paste_tabular->row_info.size() > rows)
5299                 paste_tabular->deleteRow(rows);
5300
5301         for (col_type i = 0; i < cs; ++i)
5302                 paste_tabular->deleteColumn(0);
5303
5304         col_type const columns = ce - cs + 1;
5305         while (paste_tabular->column_info.size() > columns)
5306                 paste_tabular->deleteColumn(columns);
5307
5308         paste_tabular->setBuffer(tabular.buffer());
5309
5310         odocstringstream os;
5311         OutputParams const runparams(0);
5312         paste_tabular->plaintext(os, runparams, 0, true, '\t');
5313         // Needed for the "Edit->Paste recent" menu and the system clipboard.
5314         cap::copySelection(cur, os.str());
5315
5316         // mark tabular stack dirty
5317         // FIXME: this is a workaround for bug 1919. Should be removed for 1.5,
5318         // when we (hopefully) have a one-for-all paste mechanism.
5319         // This must be called after cap::copySelection.
5320         dirtyTabularStack(true);
5321
5322         return true;
5323 }
5324
5325
5326 bool InsetTabular::pasteClipboard(Cursor & cur)
5327 {
5328         if (!paste_tabular)
5329                 return false;
5330         col_type actcol = tabular.cellColumn(cur.idx());
5331         row_type actrow = tabular.cellRow(cur.idx());
5332
5333         if (cur.selIsMultiCell()) {
5334                 row_type re;
5335                 col_type ce;
5336                 getSelection(cur, actrow, re, actcol, ce);
5337         }
5338
5339         for (row_type r1 = 0, r2 = actrow;
5340              r1 < paste_tabular->row_info.size() && r2 < tabular.row_info.size();
5341              ++r1, ++r2) {
5342                 for (col_type c1 = 0, c2 = actcol;
5343                     c1 < paste_tabular->column_info.size() && c2 < tabular.column_info.size();
5344                     ++c1, ++c2) {
5345                         if (paste_tabular->isPartOfMultiColumn(r1, c1) &&
5346                               tabular.isPartOfMultiColumn(r2, c2))
5347                                 continue;
5348                         if (paste_tabular->isPartOfMultiColumn(r1, c1)) {
5349                                 --c2;
5350                                 continue;
5351                         }
5352                         if (tabular.isPartOfMultiColumn(r2, c2)) {
5353                                 --c1;
5354                                 continue;
5355                         }
5356                         shared_ptr<InsetTableCell> inset(
5357                                 new InsetTableCell(*paste_tabular->cellInset(r1, c1)));
5358                         tabular.setCellInset(r2, c2, inset);
5359                         // FIXME?: why do we need to do this explicitly? (EL)
5360                         tabular.cellInset(r2, c2)->setBuffer(tabular.buffer());
5361
5362                         // FIXME: change tracking (MG)
5363                         inset->setChange(Change(buffer().params().trackChanges ?
5364                                                 Change::INSERTED : Change::UNCHANGED));
5365                         cur.pos() = 0;
5366                 }
5367         }
5368         return true;
5369 }
5370
5371
5372 void InsetTabular::cutSelection(Cursor & cur)
5373 {
5374         if (!cur.selection())
5375                 return;
5376
5377         row_type rs, re;
5378         col_type cs, ce;
5379         getSelection(cur, rs, re, cs, ce);
5380         for (row_type i = rs; i <= re; ++i) {
5381                 for (col_type j = cs; j <= ce; ++j) {
5382                         shared_ptr<InsetTableCell> t
5383                                 = cell(tabular.cellIndex(i, j));
5384                         if (buffer().params().trackChanges)
5385                                 // FIXME: Change tracking (MG)
5386                                 t->setChange(Change(Change::DELETED));
5387                         else
5388                                 t->clear();
5389                 }
5390         }
5391
5392         // cursor position might be invalid now
5393         if (cur.pit() > cur.lastpit())
5394                 cur.pit() = cur.lastpit();
5395         if (cur.pos() > cur.lastpos())
5396                 cur.pos() = cur.lastpos();
5397         cur.clearSelection();
5398 }
5399
5400
5401 bool InsetTabular::isRightToLeft(Cursor & cur) const
5402 {
5403         LASSERT(cur.depth() > 1, /**/);
5404         Paragraph const & parentpar = cur[cur.depth() - 2].paragraph();
5405         pos_type const parentpos = cur[cur.depth() - 2].pos();
5406         return parentpar.getFontSettings(buffer().params(),
5407                                          parentpos).language()->rightToLeft();
5408 }
5409
5410 docstring InsetTabular::asString(idx_type stidx, idx_type enidx, 
5411                                  bool intoInsets)
5412 {
5413         LASSERT(stidx <= enidx, return docstring());
5414         docstring retval;
5415         col_type const col1 = tabular.cellColumn(stidx);
5416         col_type const col2 = tabular.cellColumn(enidx);
5417         row_type const row1 = tabular.cellRow(stidx);
5418         row_type const row2 = tabular.cellRow(enidx);
5419         bool first = true;
5420         for (col_type col = col1; col <= col2; col++)
5421                 for (row_type row = row1; row <= row2; row++) {
5422                         if (!first)
5423                                 retval += "\n";
5424                         else
5425                                 first = false;
5426                         retval += tabular.cellInset(row, col)->asString(intoInsets);
5427                 }
5428         return retval;
5429 }
5430
5431
5432 void InsetTabular::getSelection(Cursor & cur,
5433         row_type & rs, row_type & re, col_type & cs, col_type & ce) const
5434 {
5435         CursorSlice const & beg = cur.selBegin();
5436         CursorSlice const & end = cur.selEnd();
5437         cs = tabular.cellColumn(beg.idx());
5438         ce = tabular.cellColumn(end.idx());
5439         if (cs > ce) {
5440                 ce = cs;
5441                 cs = tabular.cellColumn(end.idx());
5442         } else {
5443                 ce = tabular.cellRightColumn(end.idx());
5444         }
5445
5446         rs = tabular.cellRow(beg.idx());
5447         re = tabular.cellRow(end.idx());
5448         if (rs > re)
5449                 swap(rs, re);
5450 }
5451
5452
5453 Text * InsetTabular::getText(int idx) const
5454 {
5455         return size_t(idx) < nargs() ? cell(idx)->getText(0) : 0;
5456 }
5457
5458
5459 void InsetTabular::setChange(Change const & change)
5460 {
5461         for (idx_type idx = 0; idx < nargs(); ++idx)
5462                 cell(idx)->setChange(change);
5463 }
5464
5465
5466 void InsetTabular::acceptChanges()
5467 {
5468         for (idx_type idx = 0; idx < nargs(); ++idx)
5469                 cell(idx)->acceptChanges();
5470 }
5471
5472
5473 void InsetTabular::rejectChanges()
5474 {
5475         for (idx_type idx = 0; idx < nargs(); ++idx)
5476                 cell(idx)->rejectChanges();
5477 }
5478
5479
5480 bool InsetTabular::allowParagraphCustomization(idx_type cell) const
5481 {
5482         return tabular.getPWidth(cell).zero();
5483 }
5484
5485
5486 bool InsetTabular::forcePlainLayout(idx_type cell) const
5487 {
5488         return !tabular.getPWidth(cell).zero();
5489 }
5490
5491
5492 bool InsetTabular::insertPlaintextString(BufferView & bv, docstring const & buf,
5493                                      bool usePaste)
5494 {
5495         if (buf.length() <= 0)
5496                 return true;
5497
5498         col_type cols = 1;
5499         row_type rows = 1;
5500         col_type maxCols = 1;
5501         size_t const len = buf.length();
5502         size_t p = 0;
5503
5504         while (p < len &&
5505                (p = buf.find_first_of(from_ascii("\t\n"), p)) != docstring::npos) {
5506                 switch (buf[p]) {
5507                 case '\t':
5508                         ++cols;
5509                         break;
5510                 case '\n':
5511                         if (p + 1 < len)
5512                                 ++rows;
5513                         maxCols = max(cols, maxCols);
5514                         cols = 1;
5515                         break;
5516                 }
5517                 ++p;
5518         }
5519         maxCols = max(cols, maxCols);
5520         Tabular * loctab;
5521         idx_type cell = 0;
5522         col_type ocol = 0;
5523         row_type row = 0;
5524         if (usePaste) {
5525                 paste_tabular.reset(new Tabular(buffer_, rows, maxCols));
5526                 loctab = paste_tabular.get();
5527                 cols = 0;
5528                 dirtyTabularStack(true);
5529         } else {
5530                 loctab = &tabular;
5531                 cell = bv.cursor().idx();
5532                 ocol = tabular.cellColumn(cell);
5533                 row = tabular.cellRow(cell);
5534         }
5535
5536         size_t op = 0;
5537         idx_type const cells = loctab->numberofcells;
5538         p = 0;
5539         cols = ocol;
5540         rows = loctab->row_info.size();
5541         col_type const columns = loctab->column_info.size();
5542
5543         while (cell < cells && p < len && row < rows &&
5544                (p = buf.find_first_of(from_ascii("\t\n"), p)) != docstring::npos)
5545         {
5546                 if (p >= len)
5547                         break;
5548                 switch (buf[p]) {
5549                 case '\t':
5550                         // we can only set this if we are not too far right
5551                         if (cols < columns) {
5552                                 shared_ptr<InsetTableCell> inset = loctab->cellInset(cell);
5553                                 Font const font = bv.textMetrics(&inset->text()).
5554                                         displayFont(0, 0);
5555                                 inset->setText(buf.substr(op, p - op), font,
5556                                                buffer().params().trackChanges);
5557                                 ++cols;
5558                                 ++cell;
5559                         }
5560                         break;
5561                 case '\n':
5562                         // we can only set this if we are not too far right
5563                         if (cols < columns) {
5564                                 shared_ptr<InsetTableCell> inset = tabular.cellInset(cell);
5565                                 Font const font = bv.textMetrics(&inset->text()).
5566                                         displayFont(0, 0);
5567                                 inset->setText(buf.substr(op, p - op), font,
5568                                                buffer().params().trackChanges);
5569                         }
5570                         cols = ocol;
5571                         ++row;
5572                         if (row < rows)
5573                                 cell = loctab->cellIndex(row, cols);
5574                         break;
5575                 }
5576                 ++p;
5577                 op = p;
5578         }
5579         // check for the last cell if there is no trailing '\n'
5580         if (cell < cells && op < len) {
5581                 shared_ptr<InsetTableCell> inset = loctab->cellInset(cell);
5582                 Font const font = bv.textMetrics(&inset->text()).displayFont(0, 0);
5583                 inset->setText(buf.substr(op, len - op), font,
5584                         buffer().params().trackChanges);
5585         }
5586         return true;
5587 }
5588
5589
5590 void InsetTabular::addPreview(DocIterator const & inset_pos,
5591         PreviewLoader & loader) const
5592 {
5593         row_type const rows = tabular.row_info.size();
5594         col_type const columns = tabular.column_info.size();
5595         DocIterator cell_pos = inset_pos;
5596
5597         cell_pos.push_back(CursorSlice(*const_cast<InsetTabular *>(this)));
5598         for (row_type i = 0; i < rows; ++i) {
5599                 for (col_type j = 0; j < columns; ++j) {
5600                         cell_pos.top().idx() = tabular.cellIndex(i, j);
5601                         tabular.cellInset(i, j)->addPreview(cell_pos, loader);
5602                 }
5603         }
5604 }
5605
5606
5607 bool InsetTabular::completionSupported(Cursor const & cur) const
5608 {
5609         Cursor const & bvCur = cur.bv().cursor();
5610         if (&bvCur.inset() != this)
5611                 return false;
5612         return cur.text()->completionSupported(cur);
5613 }
5614
5615
5616 bool InsetTabular::inlineCompletionSupported(Cursor const & cur) const
5617 {
5618         return completionSupported(cur);
5619 }
5620
5621
5622 bool InsetTabular::automaticInlineCompletion() const
5623 {
5624         return lyxrc.completion_inline_text;
5625 }
5626
5627
5628 bool InsetTabular::automaticPopupCompletion() const
5629 {
5630         return lyxrc.completion_popup_text;
5631 }
5632
5633
5634 bool InsetTabular::showCompletionCursor() const
5635 {
5636         return lyxrc.completion_cursor_text;
5637 }
5638
5639
5640 CompletionList const * InsetTabular::createCompletionList(Cursor const & cur) const
5641 {
5642         return completionSupported(cur) ? cur.text()->createCompletionList(cur) : 0;
5643 }
5644
5645
5646 docstring InsetTabular::completionPrefix(Cursor const & cur) const
5647 {
5648         if (!completionSupported(cur))
5649                 return docstring();
5650         return cur.text()->completionPrefix(cur);
5651 }
5652
5653
5654 bool InsetTabular::insertCompletion(Cursor & cur, docstring const & s, bool finished)
5655 {
5656         if (!completionSupported(cur))
5657                 return false;
5658
5659         return cur.text()->insertCompletion(cur, s, finished);
5660 }
5661
5662
5663 void InsetTabular::completionPosAndDim(Cursor const & cur, int & x, int & y, 
5664                                     Dimension & dim) const
5665 {
5666         TextMetrics const & tm = cur.bv().textMetrics(cur.text());
5667         tm.completionPosAndDim(cur, x, y, dim);
5668 }
5669
5670
5671 void InsetTabular::string2params(string const & in, InsetTabular & inset)
5672 {
5673         istringstream data(in);
5674         Lexer lex;
5675         lex.setStream(data);
5676
5677         if (in.empty())
5678                 return;
5679
5680         string token;
5681         lex >> token;
5682         if (!lex || token != "tabular") {
5683                 LYXERR0("Expected arg 1 to be \"tabular\" in " << in);
5684                 return;
5685         }
5686
5687         // This is part of the inset proper that is usually swallowed
5688         // by Buffer::readInset
5689         lex >> token;
5690         if (!lex || token != "Tabular") {
5691                 LYXERR0("Expected arg 2 to be \"Tabular\" in " << in);
5692                 return;
5693         }
5694
5695         inset.read(lex);
5696 }
5697
5698
5699 string InsetTabular::params2string(InsetTabular const & inset)
5700 {
5701         ostringstream data;
5702         data << "tabular" << ' ';
5703         inset.write(data);
5704         data << "\\end_inset\n";
5705         return data.str();
5706 }
5707
5708
5709 } // namespace lyx