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