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