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