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