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