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