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