]> git.lyx.org Git - lyx.git/blob - src/insets/InsetTabular.cpp
msvcUsing "using namespace std" with msvc10 makes also std::tr1::shared_ptr visible...
[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         if (code == MATHMACRO_CODE
3135                 || (code == CAPTION_CODE && !tabular.is_long_tabular))
3136                 return false;
3137
3138         return true;
3139 }
3140
3141
3142 void InsetTabular::write(ostream & os) const
3143 {
3144         os << "Tabular" << endl;
3145         tabular.write(os);
3146 }
3147
3148
3149 docstring InsetTabular::contextMenu(BufferView const &, int, int) const
3150 {
3151         // FIXME: depending on the selection state, we could offer a different menu.
3152         return from_ascii("context-tabular");
3153 }
3154
3155
3156 void InsetTabular::read(Lexer & lex)
3157 {
3158         //bool const old_format = (lex.getString() == "\\LyXTable");
3159
3160         tabular.read(lex);
3161
3162         //if (old_format)
3163         //      return;
3164
3165         lex.next();
3166         string token = lex.getString();
3167         while (lex && token != "\\end_inset") {
3168                 lex.next();
3169                 token = lex.getString();
3170         }
3171         if (!lex)
3172                 lex.printError("Missing \\end_inset at this point. ");
3173 }
3174
3175
3176 int InsetTabular::rowFromY(Cursor & cur, int y) const
3177 {
3178         // top y coordinate of tabular
3179         int h = yo(cur.bv()) - tabular.rowAscent(0);
3180         row_type r = 0;
3181         for (; r < tabular.nrows() && y > h; ++r)
3182                 h += tabular.rowAscent(r) + tabular.rowDescent(r)
3183                 + tabular.interRowSpace(r);
3184
3185         return r - 1;
3186 }
3187
3188
3189 int InsetTabular::columnFromX(Cursor & cur, int x) const
3190 {
3191         // left x coordinate of tabular
3192         int w = xo(cur.bv()) + ADD_TO_TABULAR_WIDTH;
3193         col_type c = 0;
3194         for (; c < tabular.ncols() && x > w; ++c)
3195                 w += tabular.columnWidth(c);
3196         return c - 1;
3197 }
3198
3199
3200 void InsetTabular::metrics(MetricsInfo & mi, Dimension & dim) const
3201 {
3202         //lyxerr << "InsetTabular::metrics: " << mi.base.bv << " width: " <<
3203         //      mi.base.textwidth << "\n";
3204         if (!mi.base.bv) {
3205                 LYXERR0("need bv");
3206                 LASSERT(false, /**/);
3207         }
3208
3209         for (row_type r = 0; r < tabular.nrows(); ++r) {
3210                 int maxasc = 0;
3211                 int maxdes = 0;
3212                 for (col_type c = 0; c < tabular.ncols(); ++c) {
3213                         if (tabular.isPartOfMultiColumn(r, c)
3214                                 || tabular.isPartOfMultiRow(r, c))
3215                                 // multicolumn or multirow cell, but not first one
3216                                 continue;
3217                         idx_type const cell = tabular.cellIndex(r, c);
3218                         Dimension dim;
3219                         MetricsInfo m = mi;
3220                         Length const p_width = tabular.getPWidth(cell);
3221                         if (!p_width.zero())
3222                                 m.base.textwidth = p_width.inPixels(mi.base.textwidth);
3223                         tabular.cellInset(cell)->metrics(m, dim);
3224                         if (!p_width.zero())
3225                                 dim.wid = m.base.textwidth;
3226                         tabular.setCellWidth(cell, dim.wid);
3227
3228                         // FIXME(?): do we need a second metrics call?
3229                         TextMetrics const & tm = 
3230                                 mi.base.bv->textMetrics(tabular.cellInset(cell)->getText(0));
3231                         // with LYX_VALIGN_BOTTOM the descent is relative to the last par
3232                         // = descent of text in last par + TEXT_TO_INSET_OFFSET:
3233                         int const lastpardes = tm.last().second->descent()
3234                                 + TEXT_TO_INSET_OFFSET;
3235                         int offset = 0;
3236                         switch (tabular.getVAlignment(cell)) { 
3237                                 case Tabular::LYX_VALIGN_TOP:
3238                                         break; 
3239                                 case Tabular::LYX_VALIGN_MIDDLE:
3240                                         offset = -(dim.des - lastpardes)/2; 
3241                                         break; 
3242                                 case Tabular::LYX_VALIGN_BOTTOM:
3243                                         offset = -(dim.des - lastpardes); 
3244                                         break;
3245                         }
3246                         tabular.cell_info[r][c].voffset = offset;
3247                         maxasc = max(maxasc, dim.asc - offset);
3248                         maxdes = max(maxdes, dim.des + offset);
3249                 }
3250                 int const top_space = tabular.row_info[r].top_space_default ?
3251                         default_line_space :
3252                         tabular.row_info[r].top_space.inPixels(mi.base.textwidth);
3253                 tabular.setRowAscent(r, maxasc + ADD_TO_HEIGHT + top_space);
3254                 int const bottom_space = tabular.row_info[r].bottom_space_default ?
3255                         default_line_space :
3256                         tabular.row_info[r].bottom_space.inPixels(mi.base.textwidth);
3257                 tabular.setRowDescent(r, maxdes + ADD_TO_HEIGHT + bottom_space);
3258         }
3259         tabular.updateColumnWidths();
3260         dim.asc = tabular.rowAscent(0);
3261         dim.des = tabular.height() - dim.asc;
3262         dim.wid = tabular.width() + 2 * ADD_TO_TABULAR_WIDTH;
3263 }
3264
3265
3266 bool InsetTabular::isCellSelected(Cursor & cur, row_type row, col_type col) 
3267         const
3268 {
3269         if (&cur.inset() == this && cur.selection()) {
3270                 if (cur.selIsMultiCell()) {
3271                         row_type rs, re;
3272                         col_type cs, ce;
3273                         getSelection(cur, rs, re, cs, ce);
3274                         
3275                         idx_type const cell = tabular.cellIndex(row, col);
3276                         col_type const cspan = tabular.columnSpan(cell);
3277                         row_type const rspan = tabular.rowSpan(cell);
3278                         if (col + cspan - 1 >= cs && col <= ce 
3279                                 && row + rspan - 1 >= rs && row <= re)
3280                                 return true;
3281                 } else 
3282                         if (col == tabular.cellColumn(cur.idx()) 
3283                                 && row == tabular.cellRow(cur.idx())) {
3284                         CursorSlice const & beg = cur.selBegin();
3285                         CursorSlice const & end = cur.selEnd();
3286
3287                         if ((end.lastpos() > 0 || end.lastpit() > 0)
3288                                   && end.pos() == end.lastpos() && beg.pos() == 0
3289                                   && end.pit() == end.lastpit() && beg.pit() == 0)
3290                                 return true;
3291                 }
3292         }
3293         return false;
3294 }
3295
3296
3297 void InsetTabular::draw(PainterInfo & pi, int x, int y) const
3298 {
3299         x += scx_ + ADD_TO_TABULAR_WIDTH;
3300
3301         BufferView * bv = pi.base.bv;
3302         Cursor & cur = pi.base.bv->cursor();
3303         resetPos(cur);
3304
3305         // FIXME: As the full background is painted in drawSelection(),
3306         // we have no choice but to do a full repaint for the Text cells.
3307         pi.full_repaint = true;
3308
3309         bool const original_selection_state = pi.selected;
3310
3311         idx_type idx = 0;
3312         first_visible_cell = Tabular::npos;
3313         for (row_type r = 0; r < tabular.nrows(); ++r) {
3314                 int nx = x;
3315                 for (col_type c = 0; c < tabular.ncols(); ++c) {
3316                         if (tabular.isPartOfMultiColumn(r, c))
3317                                 continue;
3318                         
3319                         idx = tabular.cellIndex(r, c);
3320                         
3321                         if (tabular.isPartOfMultiRow(r, c)) {
3322                                 nx += tabular.columnWidth(idx);
3323                                 continue;
3324                         }
3325
3326                         if (first_visible_cell == Tabular::npos)
3327                                 first_visible_cell = idx;
3328
3329                         pi.selected |= isCellSelected(cur, r, c);
3330                         int const cx = nx + tabular.textHOffset(idx);
3331                         int const cy = y  + tabular.textVOffset(idx);
3332                         // Cache the Inset position.
3333                         bv->coordCache().insets().add(cell(idx).get(), cx, cy);
3334                         cell(idx)->draw(pi, cx, cy);
3335                         drawCellLines(pi.pain, nx, y, r, idx, pi.change_);
3336                         nx += tabular.columnWidth(idx);
3337                         pi.selected = original_selection_state;
3338                 }
3339
3340                 if (r + 1 < tabular.nrows())
3341                         y += tabular.rowDescent(r) + tabular.rowAscent(r + 1) 
3342                                 + tabular.interRowSpace(r + 1);
3343         }
3344 }
3345
3346
3347 void InsetTabular::drawSelection(PainterInfo & pi, int x, int y) const
3348 {
3349         Cursor & cur = pi.base.bv->cursor();
3350         resetPos(cur);
3351
3352         x += scx_ + ADD_TO_TABULAR_WIDTH;
3353
3354         // FIXME: it is wrong to completely paint the background
3355         // if we want to do single row painting.
3356
3357         // Paint background of current tabular
3358         int const w = tabular.width();
3359         int const h = tabular.height();
3360         int yy = y - tabular.rowAscent(0);
3361         pi.pain.fillRectangle(x, yy, w, h, pi.backgroundColor(this));
3362
3363         if (!cur.selection())
3364                 return;
3365         if (&cur.inset() != this)
3366                 return;
3367
3368         //resetPos(cur);
3369
3370         bool const full_cell_selected = isCellSelected(cur,
3371                 tabular.cellRow(cur.idx()), tabular.cellColumn(cur.idx()));
3372
3373         if (cur.selIsMultiCell() || full_cell_selected) {
3374                 for (row_type r = 0; r < tabular.nrows(); ++r) {
3375                         int xx = x;
3376                         for (col_type c = 0; c < tabular.ncols(); ++c) {
3377                                 if (tabular.isPartOfMultiColumn(r, c))
3378                                         continue;
3379
3380                                 idx_type const cell = tabular.cellIndex(r, c);
3381
3382                                 if (tabular.isPartOfMultiRow(r, c)) {
3383                                         xx += tabular.columnWidth(cell);
3384                                         continue;
3385                                 }
3386                                 int const w = tabular.columnWidth(cell);
3387                                 int const h = tabular.cellHeight(cell);
3388                                 int const yy = y - tabular.rowAscent(r);
3389                                 if (isCellSelected(cur, r, c))
3390                                         pi.pain.fillRectangle(xx, yy, w, h, Color_selection);
3391                                 xx += w;
3392                         }
3393                         if (r + 1 < tabular.nrows())
3394                                 y += tabular.rowDescent(r) + tabular.rowAscent(r + 1)
3395                                      + tabular.interRowSpace(r + 1);
3396                 }
3397
3398         } else {
3399                 x += cellXPos(cur.idx());
3400                 x += tabular.textHOffset(cur.idx());
3401                 cell(cur.idx())->drawSelection(pi, x, 0 /* ignored */);
3402         }
3403 }
3404
3405
3406 void InsetTabular::drawCellLines(Painter & pain, int x, int y,
3407                                                                  row_type row, idx_type cell, Change const & change) const
3408 {
3409         y -= tabular.rowAscent(row);
3410         int const w = tabular.columnWidth(cell);
3411         int const h = tabular.cellHeight(cell);
3412         Color linecolor = change.changed() ? change.color() : Color_tabularline;
3413         Color gridcolor = change.changed() ? change.color() : Color_tabularonoffline;
3414
3415         // Top
3416         bool drawline = tabular.topLine(cell)
3417                 || (row > 0 && tabular.bottomLine(tabular.cellAbove(cell)));
3418         pain.line(x, y, x + w, y,
3419                 drawline ? linecolor : gridcolor,
3420                 drawline ? Painter::line_solid : Painter::line_onoffdash);
3421
3422         // Bottom
3423         drawline = tabular.bottomLine(cell);
3424         pain.line(x, y + h, x + w, y + h,
3425                 drawline ? linecolor : gridcolor,
3426                 drawline ? Painter::line_solid : Painter::line_onoffdash);
3427
3428         // Left
3429         col_type const col = tabular.cellColumn(cell);
3430         drawline = tabular.leftLine(cell)
3431                 || (col > 0 && tabular.rightLine(tabular.cellIndex(row, col - 1)));
3432         pain.line(x, y, x, y + h,
3433                 drawline ? linecolor : gridcolor,
3434                 drawline ? Painter::line_solid : Painter::line_onoffdash);
3435
3436         // Right
3437         x -= tabular.interColumnSpace(cell);
3438         drawline = tabular.rightLine(cell)
3439                    || (col + 1 < tabular.ncols()
3440                        && tabular.leftLine(tabular.cellIndex(row, col + 1)));
3441         pain.line(x + w, y, x + w, y + h,
3442                 drawline ? linecolor : gridcolor,
3443                 drawline ? Painter::line_solid : Painter::line_onoffdash);
3444 }
3445
3446
3447 void InsetTabular::edit(Cursor & cur, bool front, EntryDirection)
3448 {
3449         //lyxerr << "InsetTabular::edit: " << this << endl;
3450         cur.finishUndo();
3451         cur.setSelection(false);
3452         cur.push(*this);
3453         if (front) {
3454                 if (isRightToLeft(cur))
3455                         cur.idx() = tabular.getLastCellInRow(0);
3456                 else
3457                         cur.idx() = 0;
3458                 cur.pit() = 0;
3459                 cur.pos() = 0;
3460         } else {
3461                 if (isRightToLeft(cur))
3462                         cur.idx() = tabular.getFirstCellInRow(tabular.nrows() - 1);
3463                 else
3464                         cur.idx() = tabular.numberofcells - 1;
3465                 cur.pit() = 0;
3466                 cur.pos() = cur.lastpos(); // FIXME crude guess
3467         }
3468         cur.setCurrentFont();
3469         // FIXME: this accesses the position cache before it is initialized
3470         //resetPos(cur);
3471         //cur.bv().fitCursor();
3472 }
3473
3474
3475 void InsetTabular::updateBuffer(ParIterator const & it, UpdateType utype)
3476 {
3477         // In a longtable, tell captions what the current float is
3478         Counters & cnts = buffer().masterBuffer()->params().documentClass().counters();
3479         string const saveflt = cnts.current_float();
3480         if (tabular.is_long_tabular)
3481                 cnts.current_float("table");
3482
3483         ParIterator it2 = it;
3484         it2.forwardPos();
3485         size_t const end = it2.nargs();
3486         for ( ; it2.idx() < end; it2.top().forwardIdx())
3487                 buffer().updateBuffer(it2, utype);
3488
3489         //reset afterwards
3490         if (tabular.is_long_tabular)
3491                 cnts.current_float(saveflt);
3492 }
3493
3494
3495 void InsetTabular::addToToc(DocIterator const & cpit)
3496 {
3497         DocIterator dit = cpit;
3498         dit.forwardPos();
3499         size_t const end = dit.nargs();
3500         for ( ; dit.idx() < end; dit.top().forwardIdx())
3501                 cell(dit.idx())->addToToc(dit);
3502 }
3503
3504
3505 void InsetTabular::doDispatch(Cursor & cur, FuncRequest & cmd)
3506 {
3507         LYXERR(Debug::DEBUG, "# InsetTabular::doDispatch: cmd: " << cmd
3508                              << "\n  cur:" << cur);
3509         CursorSlice sl = cur.top();
3510         Cursor & bvcur = cur.bv().cursor();
3511
3512         FuncCode const act = cmd.action();
3513         
3514         switch (act) {
3515
3516         case LFUN_MOUSE_PRESS: {
3517                 //lyxerr << "# InsetTabular::MousePress\n" << cur.bv().cursor() << endl;
3518                 // select row
3519                 if (cmd.x() < xo(cur.bv()) + ADD_TO_TABULAR_WIDTH
3520                         || cmd.x() > xo(cur.bv()) + tabular.width()) {
3521                         row_type r = rowFromY(cur, cmd.y());
3522                         cur.idx() = tabular.getFirstCellInRow(r);
3523                         cur.pos() = 0;
3524                         cur.resetAnchor();
3525                         cur.idx() = tabular.getLastCellInRow(r);
3526                         cur.pos() = cur.lastpos();
3527                         cur.setSelection(true);
3528                         bvcur = cur; 
3529                         rowselect_ = true;
3530                         break;
3531                 }
3532                 // select column
3533                 int const y0 = yo(cur.bv()) - tabular.rowAscent(0);
3534                 if (cmd.y() < y0 + ADD_TO_TABULAR_WIDTH 
3535                         || cmd.y() > y0 + tabular.height()) {
3536                         col_type c = columnFromX(cur, cmd.x());
3537                         cur.idx() = tabular.cellIndex(0, c);
3538                         cur.pos() = 0;
3539                         cur.resetAnchor();
3540                         cur.idx() = tabular.cellIndex(tabular.nrows() - 1, c);
3541                         cur.pos() = cur.lastpos();
3542                         cur.setSelection(true);
3543                         bvcur = cur; 
3544                         colselect_ = true;
3545                         break;
3546                 }
3547                 // do not reset cursor/selection if we have selected
3548                 // some cells (bug 2715).
3549                 if (cmd.button() == mouse_button::button3
3550                     && &bvcur.selBegin().inset() == this 
3551                     && bvcur.selIsMultiCell()) 
3552                         ;
3553                 else
3554                         // Let InsetTableCell do it
3555                         cell(cur.idx())->dispatch(cur, cmd);
3556                 break;
3557         }
3558         case LFUN_MOUSE_MOTION:
3559                 //lyxerr << "# InsetTabular::MouseMotion\n" << bvcur << endl;
3560                 if (cmd.button() == mouse_button::button1) {
3561                         // only accept motions to places not deeper nested than the real anchor
3562                         if (!bvcur.realAnchor().hasPart(cur)) {
3563                                 cur.undispatched();
3564                                 break;
3565                         }
3566                         // select (additional) row
3567                         if (rowselect_) {
3568                                 row_type r = rowFromY(cur, cmd.y());
3569                                 cur.idx() = tabular.getLastCellInRow(r);
3570                                 // we need to reset the cursor's pit and pos now, as the old ones
3571                                 // may no longer be valid.
3572                                 cur.pit() = 0;
3573                                 cur.pos() = 0;
3574                                 bvcur.setCursor(cur);
3575                                 bvcur.setSelection(true);
3576                                 break;
3577                         }
3578                         // select (additional) column
3579                         if (colselect_) {
3580                                 col_type c = columnFromX(cur, cmd.x());
3581                                 cur.idx() = tabular.cellIndex(tabular.nrows() - 1, c);
3582                                 // we need to reset the cursor's pit and pos now, as the old ones
3583                                 // may no longer be valid.
3584                                 cur.pit() = 0;
3585                                 cur.pos() = 0;
3586                                 bvcur.setCursor(cur);
3587                                 bvcur.setSelection(true);
3588                                 break;
3589                         }
3590                         // only update if selection changes
3591                         if (bvcur.idx() == cur.idx() &&
3592                                 !(bvcur.realAnchor().idx() == cur.idx() && bvcur.pos() != cur.pos()))
3593                                 cur.noUpdate();
3594                         setCursorFromCoordinates(cur, cmd.x(), cmd.y());
3595                         bvcur.setCursor(cur);
3596                         bvcur.setSelection(true);
3597                         // if this is a multicell selection, we just set the cursor to
3598                         // the beginning of the cell's text.
3599                         if (bvcur.selIsMultiCell()) {
3600                                 bvcur.pit() = bvcur.lastpit();
3601                                 bvcur.pos() = bvcur.lastpos();
3602                         }
3603                 }
3604                 break;
3605
3606         case LFUN_MOUSE_RELEASE:
3607                 rowselect_ = false;
3608                 colselect_ = false;
3609                 break;
3610
3611         case LFUN_CELL_BACKWARD:
3612                 movePrevCell(cur);
3613                 cur.setSelection(false);
3614                 break;
3615
3616         case LFUN_CELL_FORWARD:
3617                 moveNextCell(cur);
3618                 cur.setSelection(false);
3619                 break;
3620
3621         case LFUN_CHAR_FORWARD_SELECT:
3622         case LFUN_CHAR_FORWARD:
3623         case LFUN_CHAR_BACKWARD_SELECT:
3624         case LFUN_CHAR_BACKWARD:
3625         case LFUN_CHAR_RIGHT_SELECT:
3626         case LFUN_CHAR_RIGHT:
3627         case LFUN_CHAR_LEFT_SELECT:
3628         case LFUN_CHAR_LEFT: {
3629                 // determine whether we move to next or previous cell, where to enter 
3630                 // the new cell from, and which command to "finish" (i.e., exit the
3631                 // inset) with:
3632                 bool next_cell;
3633                 EntryDirection entry_from = ENTRY_DIRECTION_IGNORE;
3634                 FuncCode finish_lfun;
3635
3636                 if (act == LFUN_CHAR_FORWARD 
3637                                 || act == LFUN_CHAR_FORWARD_SELECT) {
3638                         next_cell = true;
3639                         finish_lfun = LFUN_FINISHED_FORWARD;
3640                 }
3641                 else if (act == LFUN_CHAR_BACKWARD
3642                                 || act == LFUN_CHAR_BACKWARD_SELECT) {
3643                         next_cell = false;
3644                         finish_lfun = LFUN_FINISHED_BACKWARD;
3645                 }
3646                 // LEFT or RIGHT commands --- the interpretation will depend on the 
3647                 // table's direction.
3648                 else {
3649                         bool const right = act == LFUN_CHAR_RIGHT
3650                                 || act == LFUN_CHAR_RIGHT_SELECT;
3651                         next_cell = isRightToLeft(cur) != right;
3652                         
3653                         if (lyxrc.visual_cursor)
3654                                 entry_from = right ? ENTRY_DIRECTION_LEFT:ENTRY_DIRECTION_RIGHT;
3655
3656                         finish_lfun = right ? LFUN_FINISHED_RIGHT : LFUN_FINISHED_LEFT;
3657                 }
3658
3659                 bool const select = act == LFUN_CHAR_FORWARD_SELECT ||
3660                     act == LFUN_CHAR_BACKWARD_SELECT ||
3661                     act == LFUN_CHAR_RIGHT_SELECT ||
3662                     act == LFUN_CHAR_LEFT_SELECT;
3663
3664                 // If we have a multicell selection or we're 
3665                 // not doing some LFUN_*_SELECT thing anyway...
3666                 if (!cur.selIsMultiCell() || !select) {
3667                         col_type const c = tabular.cellColumn(cur.idx());
3668                         row_type const r = tabular.cellRow(cur.idx());
3669                         // Are we trying to select the whole cell and is the whole cell 
3670                         // not yet selected?
3671                         bool const select_whole = select && !isCellSelected(cur, r, c) &&
3672                                 ((next_cell && cur.pit() == cur.lastpit() 
3673                                 && cur.pos() == cur.lastpos())
3674                                 || (!next_cell && cur.pit() == 0 && cur.pos() == 0));
3675
3676                         bool const empty_cell = cur.lastpos() == 0 && cur.lastpit() == 0;
3677
3678                         // ...try to dispatch to the cell's inset.
3679                         cell(cur.idx())->dispatch(cur, cmd);
3680
3681                         // When we already have a selection we want to select the whole cell
3682                         // before going to the next cell.
3683                         if (select_whole && !empty_cell){
3684                                 getText(cur.idx())->selectAll(cur);
3685                                 cur.dispatched();
3686                                 break;
3687                         }
3688
3689                         // FIXME: When we support the selection of an empty cell, remove 
3690                         // the !empty_cell from this condition. For now we jump to the next
3691                         // cell if the current cell is empty.
3692                         if (cur.result().dispatched() && !empty_cell)
3693                                 break;
3694                 }
3695
3696                 // move to next/prev cell, as appropriate
3697                 // note that we will always do this if we're selecting and we have
3698                 // a multicell selection
3699                 LYXERR(Debug::RTL, "entering " << (next_cell ? "next" : "previous")
3700                         << " cell from: " << int(entry_from));
3701                 if (next_cell)
3702                         moveNextCell(cur, entry_from);
3703                 else
3704                         movePrevCell(cur, entry_from);
3705                 // if we're exiting the table, call the appropriate FINISHED lfun
3706                 if (sl == cur.top())
3707                         cmd = FuncRequest(finish_lfun);
3708                 else
3709                         cur.dispatched();
3710                 break;
3711
3712         }
3713
3714         case LFUN_DOWN_SELECT:
3715         case LFUN_DOWN:
3716                 if (!(cur.selection() && cur.selIsMultiCell()))
3717                         cell(cur.idx())->dispatch(cur, cmd);
3718                 
3719                 cur.dispatched(); // override the cell's decision
3720                 if (sl == cur.top()) {
3721                         // if our Text didn't do anything to the cursor
3722                         // then we try to put the cursor into the cell below
3723                         // setting also the right targetX.
3724                         cur.selHandle(act == LFUN_DOWN_SELECT);
3725                         if (tabular.cellRow(cur.idx()) != tabular.nrows() - 1) {
3726                                 cur.idx() = tabular.cellBelow(cur.idx());
3727                                 cur.pit() = 0;
3728                                 TextMetrics const & tm =
3729                                         cur.bv().textMetrics(cell(cur.idx())->getText(0));
3730                                 cur.pos() = tm.x2pos(cur.pit(), 0, cur.targetX());
3731                                 cur.setCurrentFont();
3732                         }
3733                 }
3734                 if (sl == cur.top()) {
3735                         // we trick it to go to forward after leaving the
3736                         // tabular.
3737                         cmd = FuncRequest(LFUN_FINISHED_FORWARD);
3738                         cur.undispatched();
3739                 }
3740                 if (cur.selIsMultiCell()) {
3741                         cur.pit() = cur.lastpit();
3742                         cur.pos() = cur.lastpos();
3743                         cur.setCurrentFont();
3744                         return;
3745                 }
3746                 break;
3747
3748         case LFUN_UP_SELECT:
3749         case LFUN_UP:
3750                 if (!(cur.selection() && cur.selIsMultiCell()))
3751                         cell(cur.idx())->dispatch(cur, cmd);
3752                 cur.dispatched(); // override the cell's decision
3753                 if (sl == cur.top()) {
3754                         // if our Text didn't do anything to the cursor
3755                         // then we try to put the cursor into the cell above
3756                         // setting also the right targetX.
3757                         cur.selHandle(act == LFUN_UP_SELECT);
3758                         if (tabular.cellRow(cur.idx()) != 0) {
3759                                 cur.idx() = tabular.cellAbove(cur.idx());
3760                                 cur.pit() = cur.lastpit();
3761                                 Text const * text = cell(cur.idx())->getText(0);
3762                                 TextMetrics const & tm = cur.bv().textMetrics(text);
3763                                 ParagraphMetrics const & pm =
3764                                         tm.parMetrics(cur.lastpit());
3765                                 cur.pos() = tm.x2pos(cur.pit(), pm.rows().size()-1, cur.targetX());
3766                                 cur.setCurrentFont();
3767                         }
3768                 }
3769                 if (sl == cur.top()) {
3770                         cmd = FuncRequest(LFUN_UP);
3771                         cur.undispatched();
3772                 }
3773                 if (cur.selIsMultiCell()) {
3774                         cur.pit() = 0;
3775                         cur.pos() = cur.lastpos();
3776                         cur.setCurrentFont();
3777                         return;
3778                 }
3779                 break;
3780
3781 //      case LFUN_SCREEN_DOWN: {
3782 //              //if (hasSelection())
3783 //              //      cur.selection() = false;
3784 //              col_type const col = tabular.cellColumn(cur.idx());
3785 //              int const t =   cur.bv().top_y() + cur.bv().height();
3786 //              if (t < yo() + tabular.getHeightOfTabular()) {
3787 //                      cur.bv().scrollDocView(t);
3788 //                      cur.idx() = tabular.cellBelow(first_visible_cell) + col;
3789 //              } else {
3790 //                      cur.idx() = tabular.getFirstCellInRow(tabular.rows() - 1) + col;
3791 //              }
3792 //              cur.par() = 0;
3793 //              cur.pos() = 0;
3794 //              break;
3795 //      }
3796 //
3797 //      case LFUN_SCREEN_UP: {
3798 //              //if (hasSelection())
3799 //              //      cur.selection() = false;
3800 //              col_type const col = tabular.cellColumn(cur.idx());
3801 //              int const t =   cur.bv().top_y() + cur.bv().height();
3802 //              if (yo() < 0) {
3803 //                      cur.bv().scrollDocView(t);
3804 //                      if (yo() > 0)
3805 //                              cur.idx() = col;
3806 //                      else
3807 //                              cur.idx() = tabular.cellBelow(first_visible_cell) + col;
3808 //              } else {
3809 //                      cur.idx() = col;
3810 //              }
3811 //              cur.par() = cur.lastpar();
3812 //              cur.pos() = cur.lastpos();
3813 //              break;
3814 //      }
3815
3816         case LFUN_LAYOUT_TABULAR:
3817                 cur.bv().showDialog("tabular");
3818                 break;
3819
3820         case LFUN_INSET_MODIFY:
3821                 if (!tabularFeatures(cur, to_utf8(cmd.argument())))
3822                         cur.undispatched();
3823                 break;
3824
3825         // insert file functions
3826         case LFUN_FILE_INSERT_PLAINTEXT_PARA:
3827         case LFUN_FILE_INSERT_PLAINTEXT:
3828                 // FIXME UNICODE
3829                 if (FileName::isAbsolute(to_utf8(cmd.argument()))) {
3830                         docstring const tmpstr = cur.bv().contentsOfPlaintextFile(
3831                                 FileName(to_utf8(cmd.argument())));
3832                         if (tmpstr.empty())
3833                                 break;
3834                         cur.recordUndoInset(INSERT_UNDO);
3835                         if (insertPlaintextString(cur.bv(), tmpstr, false)) {
3836                                 // content has been replaced,
3837                                 // so cursor might be invalid
3838                                 cur.pos() = cur.lastpos();
3839                                 cur.pit() = cur.lastpit();
3840                                 bvcur.setCursor(cur);
3841                         } else
3842                                 cur.undispatched();
3843                 }
3844                 break;
3845
3846         case LFUN_CUT:
3847                 if (cur.selIsMultiCell()) {
3848                         if (copySelection(cur)) {
3849                                 cur.recordUndoInset(DELETE_UNDO);
3850                                 cutSelection(cur);
3851                         }
3852                 } else
3853                         cell(cur.idx())->dispatch(cur, cmd);
3854                 break;
3855
3856         case LFUN_SELF_INSERT:
3857                 if (cur.selIsMultiCell()) {
3858                         cur.recordUndoInset(DELETE_UNDO);
3859                         cutSelection(cur);
3860                 }
3861                 cell(cur.idx())->dispatch(cur, cmd);
3862                 break;
3863
3864         case LFUN_CHAR_DELETE_BACKWARD:
3865         case LFUN_CHAR_DELETE_FORWARD:
3866                 if (cur.selIsMultiCell()) {
3867                         cur.recordUndoInset(DELETE_UNDO);
3868                         cutSelection(cur);
3869                 } else
3870                         cell(cur.idx())->dispatch(cur, cmd);
3871                 break;
3872
3873         case LFUN_COPY:
3874                 if (!cur.selection())
3875                         break;
3876                 if (cur.selIsMultiCell()) {
3877                         cur.finishUndo();
3878                         copySelection(cur);
3879                 } else
3880                         cell(cur.idx())->dispatch(cur, cmd);
3881                 break;
3882
3883         case LFUN_CLIPBOARD_PASTE:
3884         case LFUN_PRIMARY_SELECTION_PASTE: {
3885                 docstring const clip = (act == LFUN_CLIPBOARD_PASTE) ?
3886                         theClipboard().getAsText() :
3887                         theSelection().get();
3888                 if (clip.empty())
3889                         break;
3890                 // pass to InsertPlaintextString, but
3891                 // only if we have multi-cell content
3892                 if (clip.find_first_of(from_ascii("\t\n")) != docstring::npos) {
3893                         cur.recordUndoInset(INSERT_UNDO);
3894                         if (insertPlaintextString(cur.bv(), clip, false)) {
3895                                 // content has been replaced,
3896                                 // so cursor might be invalid
3897                                 cur.pos() = cur.lastpos();
3898                                 cur.pit() = cur.lastpit();
3899                                 bvcur.setCursor(cur);
3900                                 break;
3901                         }
3902                 }
3903                 // Let the cell handle normal text
3904                 cell(cur.idx())->dispatch(cur, cmd);
3905                 break;
3906         }
3907
3908         case LFUN_PASTE:
3909                 if (!tabularStackDirty()) {
3910                         if (!cur.selIsMultiCell())
3911                                 cell(cur.idx())->dispatch(cur, cmd);
3912                         break;
3913                 }
3914                 if (theClipboard().isInternal() ||
3915                     (!theClipboard().hasInternal() && theClipboard().hasLyXContents())) {
3916                         cur.recordUndoInset(INSERT_UNDO);
3917                         pasteClipboard(cur);
3918                 }
3919                 break;
3920
3921         case LFUN_FONT_EMPH:
3922         case LFUN_FONT_BOLD:
3923         case LFUN_FONT_BOLDSYMBOL:
3924         case LFUN_FONT_ROMAN:
3925         case LFUN_FONT_NOUN:
3926         case LFUN_FONT_ITAL:
3927         case LFUN_FONT_FRAK:
3928         case LFUN_FONT_TYPEWRITER:
3929         case LFUN_FONT_SANS:
3930         case LFUN_TEXTSTYLE_APPLY:
3931         case LFUN_TEXTSTYLE_UPDATE:
3932         case LFUN_FONT_SIZE:
3933         case LFUN_FONT_UNDERLINE:
3934         case LFUN_FONT_STRIKEOUT:
3935         case LFUN_FONT_UULINE:
3936         case LFUN_FONT_UWAVE:
3937         case LFUN_LANGUAGE:
3938         case LFUN_WORD_CAPITALIZE:
3939         case LFUN_WORD_UPCASE:
3940         case LFUN_WORD_LOWCASE:
3941         case LFUN_CHARS_TRANSPOSE:
3942                 if (cur.selIsMultiCell()) {
3943                         row_type rs, re;
3944                         col_type cs, ce;
3945                         getSelection(cur, rs, re, cs, ce);
3946                         Cursor tmpcur = cur;
3947                         for (row_type r = rs; r <= re; ++r) {
3948                                 for (col_type c = cs; c <= ce; ++c) {
3949                                         // cursor follows cell:
3950                                         tmpcur.idx() = tabular.cellIndex(r, c);
3951                                         // select this cell only:
3952                                         tmpcur.pit() = 0;
3953                                         tmpcur.pos() = 0;
3954                                         tmpcur.resetAnchor();
3955                                         tmpcur.pit() = tmpcur.lastpit();
3956                                         tmpcur.pos() = tmpcur.top().lastpos();
3957                                         tmpcur.setCursor(tmpcur);
3958                                         tmpcur.setSelection();
3959                                         cell(tmpcur.idx())->dispatch(tmpcur, cmd);
3960                                 }
3961                         }
3962                         break;
3963                 } else {
3964                         cell(cur.idx())->dispatch(cur, cmd);
3965                         break;
3966                 }
3967
3968         case LFUN_INSET_SETTINGS:
3969                 // relay this lfun to Inset, not to the cell.
3970                 Inset::doDispatch(cur, cmd);
3971                 break;
3972
3973         default:
3974                 // we try to handle this event in the insets dispatch function.
3975                 cell(cur.idx())->dispatch(cur, cmd);
3976                 break;
3977         }
3978 }
3979
3980
3981 // function sets an object as defined in func_status.h:
3982 // states OK, Unknown, Disabled, On, Off.
3983 bool InsetTabular::getStatus(Cursor & cur, FuncRequest const & cmd,
3984         FuncStatus & status) const
3985 {
3986         switch (cmd.action()) {
3987         case LFUN_INSET_MODIFY: {
3988                 if (&cur.inset() != this || cmd.getArg(0) != "tabular") 
3989                         break;
3990
3991                 string const s = cmd.getArg(1);
3992                 // FIXME: We only check for the very first argument...
3993                 int action = Tabular::LAST_ACTION;
3994                 int i = 0;
3995                 for (; tabularFeature[i].action != Tabular::LAST_ACTION; ++i) {
3996                         if (tabularFeature[i].feature == s) {
3997                                 action = tabularFeature[i].action;
3998                                 break;
3999                         }
4000                 }
4001                 if (action == Tabular::LAST_ACTION) {
4002                         status.clear();
4003                         status.setUnknown(true);
4004                         return true;
4005                 }
4006
4007                 string const argument = cmd.getLongArg(2);
4008
4009                 row_type sel_row_start = 0;
4010                 row_type sel_row_end = 0;
4011                 col_type sel_col_start = 0;
4012                 col_type sel_col_end = 0;
4013                 Tabular::ltType dummyltt;
4014                 bool flag = true;
4015
4016                 getSelection(cur, sel_row_start, sel_row_end, sel_col_start, sel_col_end);
4017
4018                 switch (action) {
4019                 case Tabular::SET_PWIDTH:
4020                 case Tabular::SET_MPWIDTH:
4021                 case Tabular::SET_SPECIAL_COLUMN:
4022                 case Tabular::SET_SPECIAL_MULTICOLUMN:
4023                 case Tabular::SET_SPECIAL_MULTIROW:
4024                 case Tabular::APPEND_ROW:
4025                 case Tabular::APPEND_COLUMN:
4026                 case Tabular::DELETE_ROW:
4027                 case Tabular::DELETE_COLUMN:
4028                 case Tabular::COPY_ROW:
4029                 case Tabular::COPY_COLUMN:
4030                 case Tabular::SET_TOP_SPACE:
4031                 case Tabular::SET_BOTTOM_SPACE:
4032                 case Tabular::SET_INTERLINE_SPACE:
4033                         status.clear();
4034                         return true;
4035
4036                 case Tabular::MULTICOLUMN:
4037                         // If a row is set as longtable caption, it must not be allowed
4038                         // to unset that this row is a multicolumn.
4039                         status.setEnabled(sel_row_start == sel_row_end
4040                                 && !tabular.ltCaption(tabular.cellRow(cur.idx())));
4041                         status.setOnOff(tabular.isMultiColumn(cur.idx()));
4042                         break;
4043
4044                 case Tabular::MULTIROW:
4045                         // If a row is set as longtable caption, it must not be allowed
4046                         // to unset that this row is a multirow.
4047                         status.setEnabled(sel_col_start == sel_col_end
4048                                 && !tabular.ltCaption(tabular.cellRow(cur.idx())));
4049                         status.setOnOff(tabular.isMultiRow(cur.idx()));
4050                         break;
4051
4052                 case Tabular::SET_ALL_LINES:
4053                 case Tabular::UNSET_ALL_LINES:
4054                 case Tabular::SET_BORDER_LINES:
4055                         status.setEnabled(!tabular.ltCaption(tabular.cellRow(cur.idx())));
4056                         break;
4057
4058                 case Tabular::SET_LINE_TOP:
4059                 case Tabular::SET_LINE_BOTTOM:
4060                 case Tabular::SET_LINE_LEFT:
4061                 case Tabular::SET_LINE_RIGHT:
4062                         status.setEnabled(!tabular.ltCaption(tabular.cellRow(cur.idx())));
4063                         break;
4064
4065                 case Tabular::TOGGLE_LINE_TOP:
4066                         status.setEnabled(!tabular.ltCaption(tabular.cellRow(cur.idx())));
4067                         status.setOnOff(tabular.topLine(cur.idx()));
4068                         break;
4069
4070                 case Tabular::TOGGLE_LINE_BOTTOM:
4071                         status.setEnabled(!tabular.ltCaption(tabular.cellRow(cur.idx())));
4072                         status.setOnOff(tabular.bottomLine(cur.idx()));
4073                         break;
4074
4075                 case Tabular::TOGGLE_LINE_LEFT:
4076                         status.setEnabled(!tabular.ltCaption(tabular.cellRow(cur.idx())));
4077                         status.setOnOff(tabular.leftLine(cur.idx()));
4078                         break;
4079
4080                 case Tabular::TOGGLE_LINE_RIGHT:
4081                         status.setEnabled(!tabular.ltCaption(tabular.cellRow(cur.idx())));
4082                         status.setOnOff(tabular.rightLine(cur.idx()));
4083                         break;
4084
4085                 case Tabular::M_ALIGN_LEFT:
4086                         flag = false;
4087                 case Tabular::ALIGN_LEFT:
4088                         status.setEnabled(!tabular.isMultiRow(cur.idx()));
4089                         status.setOnOff(tabular.getAlignment(cur.idx(), flag) == LYX_ALIGN_LEFT);
4090                         break;
4091
4092                 case Tabular::M_ALIGN_RIGHT:
4093                         flag = false;
4094                 case Tabular::ALIGN_RIGHT:
4095                         status.setEnabled(!tabular.isMultiRow(cur.idx()));
4096                         status.setOnOff(tabular.getAlignment(cur.idx(), flag) == LYX_ALIGN_RIGHT);
4097                         break;
4098
4099                 case Tabular::M_ALIGN_CENTER:
4100                         flag = false;
4101                 case Tabular::ALIGN_CENTER:
4102                         status.setEnabled(!tabular.isMultiRow(cur.idx()));
4103                         status.setOnOff(tabular.getAlignment(cur.idx(), flag) == LYX_ALIGN_CENTER);
4104                         break;
4105
4106                 case Tabular::ALIGN_BLOCK:
4107                         status.setEnabled(!tabular.getPWidth(cur.idx()).zero()
4108                                 && !tabular.isMultiRow(cur.idx()));
4109                         status.setOnOff(tabular.getAlignment(cur.idx(), flag) == LYX_ALIGN_BLOCK);
4110                         break;
4111
4112                 case Tabular::M_VALIGN_TOP:
4113                         flag = false;
4114                 case Tabular::VALIGN_TOP:
4115                         status.setEnabled(!tabular.getPWidth(cur.idx()).zero()
4116                                 && !tabular.isMultiRow(cur.idx()));
4117                         status.setOnOff(
4118                                 tabular.getVAlignment(cur.idx(), flag) == Tabular::LYX_VALIGN_TOP);
4119                         break;
4120
4121                 case Tabular::M_VALIGN_BOTTOM:
4122                         flag = false;
4123                 case Tabular::VALIGN_BOTTOM:
4124                         status.setEnabled(!tabular.getPWidth(cur.idx()).zero()
4125                                 && !tabular.isMultiRow(cur.idx()));
4126                         status.setOnOff(
4127                                 tabular.getVAlignment(cur.idx(), flag) == Tabular::LYX_VALIGN_BOTTOM);
4128                         break;
4129
4130                 case Tabular::M_VALIGN_MIDDLE:
4131                         flag = false;
4132                 case Tabular::VALIGN_MIDDLE:
4133                         status.setEnabled(!tabular.getPWidth(cur.idx()).zero()
4134                                 && !tabular.isMultiRow(cur.idx()));
4135                         status.setOnOff(
4136                                 tabular.getVAlignment(cur.idx(), flag) == Tabular::LYX_VALIGN_MIDDLE);
4137                         break;
4138
4139                 case Tabular::SET_LONGTABULAR:
4140                         status.setOnOff(tabular.is_long_tabular);
4141                         break;
4142
4143                 case Tabular::UNSET_LONGTABULAR:
4144                         status.setOnOff(!tabular.is_long_tabular);
4145                         break;
4146
4147                 case Tabular::TOGGLE_ROTATE_TABULAR:
4148                 case Tabular::SET_ROTATE_TABULAR:
4149                         status.setOnOff(tabular.rotate);
4150                         break;
4151
4152                 case Tabular::TABULAR_VALIGN_TOP:
4153                         status.setOnOff(tabular.tabular_valignment 
4154                                 == Tabular::LYX_VALIGN_TOP);
4155                         break;
4156                 case Tabular::TABULAR_VALIGN_MIDDLE:
4157                         status.setOnOff(tabular.tabular_valignment 
4158                                 == Tabular::LYX_VALIGN_MIDDLE);
4159                         break;
4160                 case Tabular::TABULAR_VALIGN_BOTTOM:
4161                         status.setOnOff(tabular.tabular_valignment 
4162                                 == Tabular::LYX_VALIGN_BOTTOM);
4163                         break;
4164
4165                 case Tabular::LONGTABULAR_ALIGN_LEFT:
4166                         status.setOnOff(tabular.longtabular_alignment 
4167                                 == Tabular::LYX_LONGTABULAR_ALIGN_LEFT);
4168                         break;
4169                 case Tabular::LONGTABULAR_ALIGN_CENTER:
4170                         status.setOnOff(tabular.longtabular_alignment 
4171                                 == Tabular::LYX_LONGTABULAR_ALIGN_CENTER);
4172                         break;
4173                 case Tabular::LONGTABULAR_ALIGN_RIGHT:
4174                         status.setOnOff(tabular.longtabular_alignment 
4175                                 == Tabular::LYX_LONGTABULAR_ALIGN_RIGHT);
4176                         break;
4177
4178                 case Tabular::UNSET_ROTATE_TABULAR:
4179                         status.setOnOff(!tabular.rotate);
4180                         break;
4181
4182                 case Tabular::TOGGLE_ROTATE_CELL:
4183                 case Tabular::SET_ROTATE_CELL:
4184                         status.setOnOff(!oneCellHasRotationState(false,
4185                                 sel_row_start, sel_row_end, sel_col_start, sel_col_end));
4186                         break;
4187
4188                 case Tabular::UNSET_ROTATE_CELL:
4189                         status.setOnOff(!oneCellHasRotationState(true,
4190                                 sel_row_start, sel_row_end, sel_col_start, sel_col_end));
4191                         break;
4192
4193                 case Tabular::SET_USEBOX:
4194                         status.setOnOff(convert<int>(argument) == tabular.getUsebox(cur.idx()));
4195                         break;
4196
4197                 // every row can only be one thing:
4198                 // either a footer or header or caption
4199                 case Tabular::SET_LTFIRSTHEAD:
4200                         status.setEnabled(sel_row_start == sel_row_end
4201                                 && !tabular.ltCaption(sel_row_start));
4202                         status.setOnOff(tabular.getRowOfLTFirstHead(sel_row_start, dummyltt));
4203                         break;
4204
4205                 case Tabular::UNSET_LTFIRSTHEAD:
4206                         status.setOnOff(!tabular.getRowOfLTFirstHead(sel_row_start, dummyltt));
4207                         break;
4208
4209                 case Tabular::SET_LTHEAD:
4210                         status.setEnabled(sel_row_start == sel_row_end
4211                                 && !tabular.ltCaption(sel_row_start));
4212                         status.setOnOff(tabular.getRowOfLTHead(sel_row_start, dummyltt));
4213                         break;
4214
4215                 case Tabular::UNSET_LTHEAD:
4216                         status.setOnOff(!tabular.getRowOfLTHead(sel_row_start, dummyltt));
4217                         break;
4218
4219                 case Tabular::SET_LTFOOT:
4220                         status.setEnabled(sel_row_start == sel_row_end
4221                                 && !tabular.ltCaption(sel_row_start));
4222                         status.setOnOff(tabular.getRowOfLTFoot(sel_row_start, dummyltt));
4223                         break;
4224
4225                 case Tabular::UNSET_LTFOOT:
4226                         status.setOnOff(!tabular.getRowOfLTFoot(sel_row_start, dummyltt));
4227                         break;
4228
4229                 case Tabular::SET_LTLASTFOOT:
4230                         status.setEnabled(sel_row_start == sel_row_end
4231                                 && !tabular.ltCaption(sel_row_start));
4232                         status.setOnOff(tabular.getRowOfLTLastFoot(sel_row_start, dummyltt));
4233                         break;
4234
4235                 case Tabular::UNSET_LTLASTFOOT:
4236                         status.setOnOff(!tabular.getRowOfLTLastFoot(sel_row_start, dummyltt));
4237                         break;
4238
4239                 case Tabular::SET_LTNEWPAGE:
4240                         status.setOnOff(tabular.getLTNewPage(sel_row_start));
4241                         break;
4242
4243                 // only one row can be the caption
4244                 // and a multirow cannot be set as caption
4245                 case Tabular::TOGGLE_LTCAPTION:
4246                         status.setEnabled(sel_row_start == sel_row_end
4247                                 && !tabular.getRowOfLTFirstHead(sel_row_start, dummyltt)
4248                                 && !tabular.getRowOfLTHead(sel_row_start, dummyltt)
4249                                 && !tabular.getRowOfLTFoot(sel_row_start, dummyltt)
4250                                 && !tabular.getRowOfLTLastFoot(sel_row_start, dummyltt)
4251                                 && (!tabular.haveLTCaption()
4252                                         || tabular.ltCaption(sel_row_start))
4253                                 && !tabular.isMultiRow(sel_row_start));
4254                         status.setOnOff(tabular.ltCaption(sel_row_start));
4255                         break;
4256
4257                 case Tabular::SET_BOOKTABS:
4258                         status.setOnOff(tabular.use_booktabs);
4259                         break;
4260
4261                 case Tabular::UNSET_BOOKTABS:
4262                         status.setOnOff(!tabular.use_booktabs);
4263                         break;
4264
4265                 default:
4266                         status.clear();
4267                         status.setEnabled(false);
4268                         break;
4269                 }
4270                 return true;
4271         }
4272
4273         // These are only enabled inside tabular
4274         case LFUN_CELL_BACKWARD:
4275         case LFUN_CELL_FORWARD:
4276                 status.setEnabled(true);
4277                 return true;
4278
4279         // disable these with multiple cells selected
4280         case LFUN_INSET_INSERT:
4281         case LFUN_TABULAR_INSERT:
4282         case LFUN_FLEX_INSERT:
4283         case LFUN_FLOAT_INSERT:
4284         case LFUN_FLOAT_WIDE_INSERT:
4285         case LFUN_FOOTNOTE_INSERT:
4286         case LFUN_MARGINALNOTE_INSERT:
4287         case LFUN_MATH_INSERT:
4288         case LFUN_MATH_MODE:
4289         case LFUN_MATH_MUTATE:
4290         case LFUN_MATH_DISPLAY:
4291         case LFUN_NOTE_INSERT:
4292         case LFUN_OPTIONAL_INSERT:
4293         case LFUN_BOX_INSERT:
4294         case LFUN_BRANCH_INSERT:
4295         case LFUN_PHANTOM_INSERT:
4296         case LFUN_WRAP_INSERT:
4297         case LFUN_PREVIEW_INSERT:
4298         case LFUN_ERT_INSERT: {
4299                 if (cur.selIsMultiCell()) {
4300                         status.setEnabled(false);
4301                         return true;
4302                 } else
4303                         return cell(cur.idx())->getStatus(cur, cmd, status);
4304         }
4305
4306         // disable in non-fixed-width cells
4307         case LFUN_NEWLINE_INSERT:
4308         case LFUN_BREAK_PARAGRAPH: {
4309                 if (tabular.getPWidth(cur.idx()).zero()) {
4310                         status.setEnabled(false);
4311                         return true;
4312                 } else
4313                         return cell(cur.idx())->getStatus(cur, cmd, status);
4314         }
4315
4316         case LFUN_NEWPAGE_INSERT:
4317                 status.setEnabled(false);
4318                 return true;
4319
4320         case LFUN_PASTE:
4321                 if (tabularStackDirty() && theClipboard().isInternal()) {
4322                         if (cur.selIsMultiCell()) {
4323                                 row_type rs, re;
4324                                 col_type cs, ce;
4325                                 getSelection(cur, rs, re, cs, ce);
4326                                 if (paste_tabular && paste_tabular->ncols() == ce - cs + 1
4327                                           && paste_tabular->nrows() == re - rs + 1)
4328                                         status.setEnabled(true);        
4329                                 else {
4330                                         status.setEnabled(false);
4331                                         status.message(_("Selection size should match clipboard content."));
4332                                 }
4333                         } else
4334                                 status.setEnabled(true);
4335                         return true;
4336                 }
4337                 return cell(cur.idx())->getStatus(cur, cmd, status);
4338
4339         case LFUN_INSET_SETTINGS:
4340                 // relay this lfun to Inset, not to the cell.
4341                 return Inset::getStatus(cur, cmd, status);
4342
4343         default:
4344                 // we try to handle this event in the insets dispatch function.
4345                 return cell(cur.idx())->getStatus(cur, cmd, status);
4346         }
4347         return false;
4348 }
4349
4350
4351 Inset::DisplayType InsetTabular::display() const
4352 {
4353                 if (tabular.is_long_tabular) {
4354                         switch (tabular.longtabular_alignment) {
4355                         case Tabular::LYX_LONGTABULAR_ALIGN_LEFT:
4356                                 return AlignLeft;
4357                         case Tabular::LYX_LONGTABULAR_ALIGN_CENTER:
4358                                 return AlignCenter;
4359                         case Tabular::LYX_LONGTABULAR_ALIGN_RIGHT:
4360                                 return AlignRight;
4361                         default:
4362                                 return AlignCenter;
4363                         }
4364                 } else
4365                         return Inline;
4366 }
4367
4368
4369 int InsetTabular::latex(odocstream & os, OutputParams const & runparams) const
4370 {
4371         return tabular.latex(os, runparams);
4372 }
4373
4374
4375 int InsetTabular::plaintext(odocstream & os, OutputParams const & runparams) const
4376 {
4377         os << '\n'; // output table on a new line
4378         int const dp = runparams.linelen > 0 ? runparams.depth : 0;
4379         tabular.plaintext(os, runparams, dp, false, 0);
4380         return PLAINTEXT_NEWLINE;
4381 }
4382
4383
4384 int InsetTabular::docbook(odocstream & os, OutputParams const & runparams) const
4385 {
4386         int ret = 0;
4387         Inset * master = 0;
4388
4389         // FIXME: Why not pass a proper DocIterator here?
4390 #if 0
4391         // if the table is inside a float it doesn't need the informaltable
4392         // wrapper. Search for it.
4393         for (master = owner(); master; master = master->owner())
4394                 if (master->lyxCode() == FLOAT_CODE)
4395                         break;
4396 #endif
4397
4398         if (!master) {
4399                 os << "<informaltable>";
4400                 ++ret;
4401         }
4402         ret += tabular.docbook(os, runparams);
4403         if (!master) {
4404                 os << "</informaltable>";
4405                 ++ret;
4406         }
4407         return ret;
4408 }
4409
4410
4411 docstring InsetTabular::xhtml(XHTMLStream & xs, OutputParams const & rp) const
4412 {
4413         // FIXME XHTML
4414         // It'd be better to be able to get this from an InsetLayout, but at present
4415         // InsetLayouts do not seem really to work for things that aren't InsetTexts.
4416         xs << html::StartTag("table");
4417         docstring ret = tabular.xhtml(xs, rp);
4418         xs << html::EndTag("table");
4419         return ret;
4420 }
4421
4422
4423 void InsetTabular::validate(LaTeXFeatures & features) const
4424 {
4425         tabular.validate(features);
4426         // FIXME XHTML
4427         // It'd be better to be able to get this from an InsetLayout, but at present
4428         // InsetLayouts do not seem really to work for things that aren't InsetTexts.
4429         if (features.runparams().flavor == OutputParams::HTML)
4430                 features.addPreambleSnippet("<style type=\"text/css\">\n"
4431       "table { border: 1px solid black; display: inline-block; }\n"
4432       "td { border: 1px solid black; padding: 0.5ex; }\n"
4433       "</style>");
4434 }
4435
4436
4437 shared_ptr<InsetTableCell const> InsetTabular::cell(idx_type idx) const
4438 {
4439         return tabular.cellInset(idx);
4440 }
4441
4442
4443 shared_ptr<InsetTableCell> InsetTabular::cell(idx_type idx)
4444 {
4445         return tabular.cellInset(idx);
4446 }
4447
4448
4449 void InsetTabular::cursorPos(BufferView const & bv,
4450                 CursorSlice const & sl, bool boundary, int & x, int & y) const
4451 {
4452         cell(sl.idx())->cursorPos(bv, sl, boundary, x, y);
4453
4454         int const row = tabular.cellRow(sl.idx());
4455         int const col = tabular.cellColumn(sl.idx());
4456
4457         // y offset     correction
4458         for (int r = 0; r < row; ++r)
4459                 y += tabular.rowDescent(r) + tabular.rowAscent(r + 1) 
4460                         + tabular.interRowSpace(r + 1);
4461
4462         y += tabular.textVOffset(sl.idx());
4463
4464         // x offset correction
4465         for (int c = 0; c < col; ++c)
4466                 x += tabular.column_info[c].width;
4467         
4468         x += tabular.textHOffset(sl.idx());
4469         x += ADD_TO_TABULAR_WIDTH;
4470         x += scx_;
4471 }
4472
4473
4474 int InsetTabular::dist(BufferView & bv, idx_type const cell, int x, int y) const
4475 {
4476         int xx = 0;
4477         int yy = 0;
4478         Inset const & inset = *tabular.cellInset(cell);
4479         Point o = bv.coordCache().getInsets().xy(&inset);
4480         int const xbeg = o.x_ - tabular.textHOffset(cell);
4481         int const xend = xbeg + tabular.columnWidth(cell);
4482         row_type const row = tabular.cellRow(cell);
4483         int const ybeg = o.y_ - tabular.rowAscent(row)
4484                 - tabular.interRowSpace(row);
4485         int const yend = ybeg + tabular.cellHeight(cell);
4486
4487         if (x < xbeg)
4488                 xx = xbeg - x;
4489         else if (x > xend)
4490                 xx = x - xend;
4491
4492         if (y < ybeg)
4493                 yy = ybeg - y;
4494         else if (y > yend)
4495                 yy = y - yend;
4496
4497         //lyxerr << " xbeg=" << xbeg << "  xend=" << xend
4498         //       << " ybeg=" << ybeg << " yend=" << yend
4499         //       << " xx=" << xx << " yy=" << yy
4500         //       << " dist=" << xx + yy << endl;
4501         return xx + yy;
4502 }
4503
4504
4505 Inset * InsetTabular::editXY(Cursor & cur, int x, int y)
4506 {
4507         //lyxerr << "InsetTabular::editXY: " << this << endl;
4508         cur.setSelection(false);
4509         cur.push(*this);
4510         cur.idx() = getNearestCell(cur.bv(), x, y);
4511         resetPos(cur);
4512         return cur.bv().textMetrics(&cell(cur.idx())->text()).editXY(cur, x, y);
4513 }
4514
4515
4516 void InsetTabular::setCursorFromCoordinates(Cursor & cur, int x, int y) const
4517 {
4518         cur.idx() = getNearestCell(cur.bv(), x, y);
4519         cur.bv().textMetrics(&cell(cur.idx())->text()).setCursorFromCoordinates(cur, x, y);
4520 }
4521
4522
4523 InsetTabular::idx_type InsetTabular::getNearestCell(BufferView & bv, int x, int y) const
4524 {
4525         idx_type idx_min = 0;
4526         int dist_min = numeric_limits<int>::max();
4527         for (idx_type i = 0, n = nargs(); i != n; ++i) {
4528                 if (bv.coordCache().getInsets().has(tabular.cellInset(i).get())) {
4529                         int const d = dist(bv, i, x, y);
4530                         if (d < dist_min) {
4531                                 dist_min = d;
4532                                 idx_min = i;
4533                         }
4534                 }
4535         }
4536         return idx_min;
4537 }
4538
4539
4540 int InsetTabular::cellXPos(idx_type const cell) const
4541 {
4542         col_type col = tabular.cellColumn(cell);
4543         int lx = 0;
4544         for (col_type c = 0; c < col; ++c)
4545                 lx += tabular.columnWidth(c);
4546
4547         return lx;
4548 }
4549
4550
4551 void InsetTabular::resetPos(Cursor & cur) const
4552 {
4553         BufferView & bv = cur.bv();
4554         int const maxwidth = bv.workWidth();
4555
4556         int const scx_old = scx_;
4557         int const i = cur.find(this);
4558         if (i == -1) {
4559                 scx_ = 0;
4560         } else {
4561                 int const X1 = 0;
4562                 int const X2 = maxwidth;
4563                 int const offset = ADD_TO_TABULAR_WIDTH + 2;
4564                 int const x1 = xo(cur.bv()) + cellXPos(cur[i].idx()) + offset;
4565                 int const x2 = x1 + tabular.columnWidth(cur[i].idx());
4566
4567                 if (x1 < X1)
4568                         scx_ = X1 + 20 - x1;
4569                 else if (x2 > X2)
4570                         scx_ = X2 - 20 - x2;
4571                 else
4572                         scx_ = 0;
4573         }
4574
4575         // only update if offset changed
4576         if (scx_ != scx_old)
4577                 cur.updateFlags(Update::Force | Update::FitCursor);
4578 }
4579
4580
4581 void InsetTabular::moveNextCell(Cursor & cur, EntryDirection entry_from)
4582 {
4583         row_type const row = tabular.cellRow(cur.idx());
4584         col_type const col = tabular.cellColumn(cur.idx());
4585
4586         if (isRightToLeft(cur)) {
4587                 if (tabular.cellColumn(cur.idx()) == 0) {
4588                         if (row == tabular.nrows() - 1)
4589                                 return;
4590                         cur.idx() = tabular.cellBelow(tabular.getLastCellInRow(row));
4591                 } else {
4592                         if (cur.idx() == 0)
4593                                 return;
4594                         if (col == 0)
4595                                 cur.idx() = tabular.getLastCellInRow(row - 1);
4596                         else
4597                                 cur.idx() = tabular.cellIndex(row, col - 1);
4598                 }
4599         } else {
4600                 if (tabular.isLastCell(cur.idx()))
4601                         return;
4602                 if (cur.idx() == tabular.getLastCellInRow(row))
4603                         cur.idx() = tabular.cellIndex(row + 1, 0);
4604                 else {
4605                         col_type const colnextcell = col + tabular.columnSpan(cur.idx());
4606                         cur.idx() = tabular.cellIndex(row, colnextcell);
4607                 }
4608         }
4609
4610         cur.boundary(false);
4611
4612         if (cur.selIsMultiCell()) {
4613                 cur.pit() = cur.lastpit();
4614                 cur.pos() = cur.lastpos();
4615                 resetPos(cur);
4616                 return;
4617         }
4618
4619         cur.pit() = 0;
4620         cur.pos() = 0;
4621
4622         // in visual mode, place cursor at extreme left or right
4623         
4624         switch(entry_from) {
4625
4626         case ENTRY_DIRECTION_RIGHT:
4627                 cur.posVisToRowExtremity(false /* !left */);
4628                 break;
4629         case ENTRY_DIRECTION_LEFT:
4630                 cur.posVisToRowExtremity(true /* left */);
4631                 break;
4632         case ENTRY_DIRECTION_IGNORE:
4633                 // nothing to do in this case
4634                 break;
4635
4636         }
4637         cur.setCurrentFont();
4638         resetPos(cur);
4639 }
4640
4641
4642 void InsetTabular::movePrevCell(Cursor & cur, EntryDirection entry_from)
4643 {
4644         row_type const row = tabular.cellRow(cur.idx());
4645         col_type const col = tabular.cellColumn(cur.idx());
4646
4647         if (isRightToLeft(cur)) {
4648                 if (cur.idx() == tabular.getLastCellInRow(row)) {
4649                         if (row == 0)
4650                                 return;
4651                         cur.idx() = tabular.getFirstCellInRow(row);
4652                         cur.idx() = tabular.cellAbove(cur.idx());
4653                 } else {
4654                         if (tabular.isLastCell(cur.idx()))
4655                                 return;
4656                         if (cur.idx() == tabular.getLastCellInRow(row))
4657                                 cur.idx() = tabular.cellIndex(row + 1, 0);
4658                         else
4659                                 cur.idx() = tabular.cellIndex(row, col + 1);
4660                 }
4661         } else {
4662                 if (cur.idx() == 0) // first cell
4663                         return;
4664                 if (col == 0)
4665                         cur.idx() = tabular.getLastCellInRow(row - 1);
4666                 else
4667                         cur.idx() = tabular.cellIndex(row, col - 1);
4668         }
4669
4670         if (cur.selIsMultiCell()) {
4671                 cur.pit() = cur.lastpit();
4672                 cur.pos() = cur.lastpos();
4673                 resetPos(cur);
4674                 return;
4675         }
4676
4677         cur.pit() = cur.lastpit();
4678         cur.pos() = cur.lastpos();
4679
4680         // in visual mode, place cursor at extreme left or right
4681         
4682         switch(entry_from) {
4683
4684         case ENTRY_DIRECTION_RIGHT:
4685                 cur.posVisToRowExtremity(false /* !left */);
4686                 break;
4687         case ENTRY_DIRECTION_LEFT:
4688                 cur.posVisToRowExtremity(true /* left */);
4689                 break;
4690         case ENTRY_DIRECTION_IGNORE:
4691                 // nothing to do in this case
4692                 break;
4693
4694         }
4695         cur.setCurrentFont();
4696         resetPos(cur);
4697 }
4698
4699
4700 bool InsetTabular::tabularFeatures(Cursor & cur, string const & argument)
4701 {
4702         istringstream is(argument);
4703         string s;
4704         is >> s;
4705         if (insetCode(s) != TABULAR_CODE)
4706                 return false;
4707
4708         // Safe guard.
4709         size_t safe_guard = 0;
4710         for (;;) {
4711                 if (is.eof())
4712                         break;
4713                 safe_guard++;
4714                 if (safe_guard > 1000) {
4715                         LYXERR0("parameter max count reached!");
4716                         break;
4717                 }
4718                 is >> s;
4719                 Tabular::Feature action = Tabular::LAST_ACTION;
4720
4721                 size_t i = 0;
4722                 for (; tabularFeature[i].action != Tabular::LAST_ACTION; ++i) {
4723                         if (s != tabularFeature[i].feature)
4724                                 continue;
4725
4726                         action = tabularFeature[i].action;
4727                         break;
4728                 }
4729                 if (action == Tabular::LAST_ACTION) {
4730                         LYXERR0("Feature not found " << s);
4731                         continue;
4732                 }
4733                 string val;
4734                 if (tabularFeature[i].need_value)
4735                         is >> val;
4736                 LYXERR(Debug::DEBUG, "Feature: " << s << "\t\tvalue: " << val);
4737                 tabularFeatures(cur, action, val);
4738         }
4739         return true;
4740 }
4741
4742
4743 static void checkLongtableSpecial(Tabular::ltType & ltt,
4744                           string const & special, bool & flag)
4745 {
4746         if (special == "dl_above") {
4747                 ltt.topDL = flag;
4748                 ltt.set = false;
4749         } else if (special == "dl_below") {
4750                 ltt.bottomDL = flag;
4751                 ltt.set = false;
4752         } else if (special == "empty") {
4753                 ltt.empty = flag;
4754                 ltt.set = false;
4755         } else if (flag) {
4756                 ltt.empty = false;
4757                 ltt.set = true;
4758         }
4759 }
4760
4761
4762 bool InsetTabular::oneCellHasRotationState(bool rotated,
4763                 row_type row_start, row_type row_end,
4764                 col_type col_start, col_type col_end) const 
4765 {
4766         for (row_type r = row_start; r <= row_end; ++r)
4767                 for (col_type c = col_start; c <= col_end; ++c)
4768                         if (tabular.getRotateCell(tabular.cellIndex(r, c)) == rotated)
4769                                 return true;
4770
4771         return false;
4772 }
4773
4774 void InsetTabular::tabularFeatures(Cursor & cur,
4775         Tabular::Feature feature, string const & value)
4776 {
4777         col_type sel_col_start;
4778         col_type sel_col_end;
4779         row_type sel_row_start;
4780         row_type sel_row_end;
4781         bool setLines = false;
4782         LyXAlignment setAlign = LYX_ALIGN_LEFT;
4783         Tabular::VAlignment setVAlign = Tabular::LYX_VALIGN_TOP;
4784
4785         switch (feature) {
4786
4787         case Tabular::M_ALIGN_LEFT:
4788         case Tabular::ALIGN_LEFT:
4789                 setAlign = LYX_ALIGN_LEFT;
4790                 break;
4791
4792         case Tabular::M_ALIGN_RIGHT:
4793         case Tabular::ALIGN_RIGHT:
4794                 setAlign = LYX_ALIGN_RIGHT;
4795                 break;
4796
4797         case Tabular::M_ALIGN_CENTER:
4798         case Tabular::ALIGN_CENTER:
4799                 setAlign = LYX_ALIGN_CENTER;
4800                 break;
4801
4802         case Tabular::ALIGN_BLOCK:
4803                 setAlign = LYX_ALIGN_BLOCK;
4804                 break;
4805
4806         case Tabular::M_VALIGN_TOP:
4807         case Tabular::VALIGN_TOP:
4808                 setVAlign = Tabular::LYX_VALIGN_TOP;
4809                 break;
4810
4811         case Tabular::M_VALIGN_BOTTOM:
4812         case Tabular::VALIGN_BOTTOM:
4813                 setVAlign = Tabular::LYX_VALIGN_BOTTOM;
4814                 break;
4815
4816         case Tabular::M_VALIGN_MIDDLE:
4817         case Tabular::VALIGN_MIDDLE:
4818                 setVAlign = Tabular::LYX_VALIGN_MIDDLE;
4819                 break;
4820
4821         default:
4822                 break;
4823         }
4824
4825         cur.recordUndoInset(ATOMIC_UNDO);
4826
4827         getSelection(cur, sel_row_start, sel_row_end, sel_col_start, sel_col_end);
4828         row_type const row = tabular.cellRow(cur.idx());
4829         col_type const column = tabular.cellColumn(cur.idx());
4830         bool flag = true;
4831         Tabular::ltType ltt;
4832
4833         switch (feature) {
4834
4835         case Tabular::SET_PWIDTH: {
4836                 Length const len(value);
4837                 tabular.setColumnPWidth(cur, cur.idx(), len);
4838                 if (len.zero()
4839                     && tabular.getAlignment(cur.idx(), true) == LYX_ALIGN_BLOCK)
4840                         tabularFeatures(cur, Tabular::ALIGN_CENTER, string());
4841                 break;
4842         }
4843
4844         case Tabular::SET_MPWIDTH:
4845                 tabular.setMColumnPWidth(cur, cur.idx(), Length(value));
4846                 break;
4847
4848         case Tabular::SET_SPECIAL_COLUMN:
4849         case Tabular::SET_SPECIAL_MULTICOLUMN:
4850                 if (value == "none")
4851                         tabular.setAlignSpecial(cur.idx(), docstring(), feature);
4852                 else
4853                         tabular.setAlignSpecial(cur.idx(), from_utf8(value), feature);
4854                 break;
4855
4856         case Tabular::SET_SPECIAL_MULTIROW:
4857                 // nothing to do
4858                 break;
4859
4860         case Tabular::APPEND_ROW:
4861                 // append the row into the tabular
4862                 tabular.appendRow(cur.idx());
4863                 break;
4864
4865         case Tabular::APPEND_COLUMN:
4866                 // append the column into the tabular
4867                 tabular.appendColumn(cur.idx());
4868                 cur.idx() = tabular.cellIndex(row, column);
4869                 break;
4870
4871         case Tabular::DELETE_ROW:
4872                 for (row_type r = sel_row_start; r <= sel_row_end; ++r)
4873                         tabular.deleteRow(sel_row_start);
4874                 if (sel_row_start >= tabular.nrows())
4875                         --sel_row_start;
4876                 cur.idx() = tabular.cellIndex(sel_row_start, column);
4877                 cur.pit() = 0;
4878                 cur.pos() = 0;
4879                 cur.setSelection(false);
4880                 break;
4881
4882         case Tabular::DELETE_COLUMN:
4883                 for (col_type c = sel_col_start; c <= sel_col_end; ++c)
4884                         tabular.deleteColumn(sel_col_start);
4885                 if (sel_col_start >= tabular.ncols())
4886                         --sel_col_start;
4887                 cur.idx() = tabular.cellIndex(row, sel_col_start);
4888                 cur.pit() = 0;
4889                 cur.pos() = 0;
4890                 cur.setSelection(false);
4891                 break;
4892
4893         case Tabular::COPY_ROW:
4894                 tabular.copyRow(row);
4895                 break;
4896
4897         case Tabular::COPY_COLUMN:
4898                 tabular.copyColumn(column);
4899                 cur.idx() = tabular.cellIndex(row, column);
4900                 break;
4901
4902         case Tabular::SET_LINE_TOP:
4903         case Tabular::TOGGLE_LINE_TOP: {
4904                 bool lineSet = (feature == Tabular::SET_LINE_TOP)
4905                                ? (value == "true") : !tabular.topLine(cur.idx());
4906                 for (row_type r = sel_row_start; r <= sel_row_end; ++r)
4907                         for (col_type c = sel_col_start; c <= sel_col_end; ++c)
4908                                 tabular.setTopLine(tabular.cellIndex(r, c), lineSet);
4909                 break;
4910         }
4911
4912         case Tabular::SET_LINE_BOTTOM:
4913         case Tabular::TOGGLE_LINE_BOTTOM: {
4914                 bool lineSet = (feature == Tabular::SET_LINE_BOTTOM)
4915                                ? (value == "true") : !tabular.bottomLine(cur.idx());
4916                 for (row_type r = sel_row_start; r <= sel_row_end; ++r)
4917                         for (col_type c = sel_col_start; c <= sel_col_end; ++c)
4918                                 tabular.setBottomLine(tabular.cellIndex(r, c), lineSet);
4919                 break;
4920         }
4921
4922         case Tabular::SET_LINE_LEFT:
4923         case Tabular::TOGGLE_LINE_LEFT: {
4924                 bool lineSet = (feature == Tabular::SET_LINE_LEFT)
4925                                ? (value == "true") : !tabular.leftLine(cur.idx());
4926                 for (row_type r = sel_row_start; r <= sel_row_end; ++r)
4927                         for (col_type c = sel_col_start; c <= sel_col_end; ++c)
4928                                 tabular.setLeftLine(tabular.cellIndex(r, c), lineSet);
4929                 break;
4930         }
4931
4932         case Tabular::SET_LINE_RIGHT:
4933         case Tabular::TOGGLE_LINE_RIGHT: {
4934                 bool lineSet = (feature == Tabular::SET_LINE_RIGHT)
4935                                ? (value == "true") : !tabular.rightLine(cur.idx());
4936                 for (row_type r = sel_row_start; r <= sel_row_end; ++r)
4937                         for (col_type c = sel_col_start; c <= sel_col_end; ++c)
4938                                 tabular.setRightLine(tabular.cellIndex(r, c), lineSet);
4939                 break;
4940         }
4941
4942         case Tabular::M_ALIGN_LEFT:
4943         case Tabular::M_ALIGN_RIGHT:
4944         case Tabular::M_ALIGN_CENTER:
4945                 flag = false;
4946         case Tabular::ALIGN_LEFT:
4947         case Tabular::ALIGN_RIGHT:
4948         case Tabular::ALIGN_CENTER:
4949         case Tabular::ALIGN_BLOCK:
4950                 for (row_type r = sel_row_start; r <= sel_row_end; ++r)
4951                         for (col_type c = sel_col_start; c <= sel_col_end; ++c)
4952                                 tabular.setAlignment(tabular.cellIndex(r, c), setAlign, flag);
4953                 break;
4954
4955         case Tabular::M_VALIGN_TOP:
4956         case Tabular::M_VALIGN_BOTTOM:
4957         case Tabular::M_VALIGN_MIDDLE:
4958                 flag = false;
4959         case Tabular::VALIGN_TOP:
4960         case Tabular::VALIGN_BOTTOM:
4961         case Tabular::VALIGN_MIDDLE:
4962                 for (row_type r = sel_row_start; r <= sel_row_end; ++r)
4963                         for (col_type c = sel_col_start; c <= sel_col_end; ++c)
4964                                 tabular.setVAlignment(tabular.cellIndex(r, c), setVAlign, flag);
4965                 break;
4966
4967         case Tabular::MULTICOLUMN: {
4968                 if (!cur.selection()) {
4969                         // just multicol for one single cell
4970                         // check whether we are completely in a multicol
4971                         if (tabular.isMultiColumn(cur.idx()))
4972                                 tabular.unsetMultiColumn(cur.idx());
4973                         else
4974                                 tabular.setMultiColumn(cur.idx(), 1);
4975                         break;
4976                 }
4977                 // we have a selection so this means we just add all this
4978                 // cells to form a multicolumn cell
4979                 idx_type const s_start = cur.selBegin().idx();
4980                 row_type const col_start = tabular.cellColumn(s_start);
4981                 row_type const col_end = tabular.cellColumn(cur.selEnd().idx());
4982                 cur.idx() = tabular.setMultiColumn(s_start, col_end - col_start + 1);
4983                 cur.pit() = 0;
4984                 cur.pos() = 0;
4985                 cur.setSelection(false);
4986                 break;
4987         }
4988         
4989         case Tabular::MULTIROW: {
4990                 if (!cur.selection()) {
4991                         // just multirow for one single cell
4992                         // check whether we are completely in a multirow
4993                         if (tabular.isMultiRow(cur.idx()))
4994                                 tabular.unsetMultiRow(cur.idx());
4995                         else
4996                                 tabular.setMultiRow(cur.idx(), 1);
4997                         break;
4998                 }
4999                 // we have a selection so this means we just add all this
5000                 // cells to form a multirow cell
5001                 idx_type const s_start = cur.selBegin().idx();
5002                 row_type const row_start = tabular.cellRow(s_start);
5003                 row_type const row_end = tabular.cellRow(cur.selEnd().idx());
5004                 cur.idx() = tabular.setMultiRow(s_start, row_end - row_start + 1);
5005                 cur.pit() = 0;
5006                 cur.pos() = 0;
5007                 cur.setSelection(false);
5008                 break;
5009         }
5010
5011         case Tabular::SET_ALL_LINES:
5012                 setLines = true;
5013         case Tabular::UNSET_ALL_LINES:
5014                 for (row_type r = sel_row_start; r <= sel_row_end; ++r)
5015                         for (col_type c = sel_col_start; c <= sel_col_end; ++c) {
5016                                 idx_type const cell = tabular.cellIndex(r, c);
5017                                 tabular.setTopLine(cell, setLines);
5018                                 tabular.setBottomLine(cell, setLines);
5019                                 tabular.setRightLine(cell, setLines);
5020                                 tabular.setLeftLine(cell, setLines);
5021                         }
5022                 break;
5023
5024         case Tabular::SET_BORDER_LINES:
5025                 for (row_type r = sel_row_start; r <= sel_row_end; ++r) {
5026                         tabular.setLeftLine(tabular.cellIndex(r, sel_col_start), true);
5027                         tabular.setRightLine(tabular.cellIndex(r, sel_col_end), true);
5028                 }
5029                 for (col_type c = sel_col_start; c <= sel_col_end; ++c) {
5030                         tabular.setTopLine(tabular.cellIndex(sel_row_start, c), true);
5031                         tabular.setBottomLine(tabular.cellIndex(sel_row_end, c), true);
5032                 }
5033                 break;
5034
5035         case Tabular::SET_LONGTABULAR:
5036                 tabular.is_long_tabular = true;
5037                 break;
5038
5039         case Tabular::UNSET_LONGTABULAR:
5040                 for (row_type r = 0; r < tabular.nrows(); ++r) {
5041                         if (tabular.ltCaption(r)) {
5042                                 cur.idx() = tabular.cellIndex(r, 0);
5043                                 cur.pit() = 0;
5044                                 cur.pos() = 0;
5045                                 tabularFeatures(cur, Tabular::TOGGLE_LTCAPTION);
5046                         }
5047                 }
5048                 tabular.is_long_tabular = false;
5049                 break;
5050
5051         case Tabular::SET_ROTATE_TABULAR:
5052                 tabular.rotate = true;
5053                 break;
5054
5055         case Tabular::UNSET_ROTATE_TABULAR:
5056                 tabular.rotate = false;
5057                 break;
5058
5059         case Tabular::TOGGLE_ROTATE_TABULAR:
5060                 tabular.rotate = !tabular.rotate;
5061                 break;
5062
5063         case Tabular::TABULAR_VALIGN_TOP:
5064                 tabular.tabular_valignment = Tabular::LYX_VALIGN_TOP;
5065                 break;
5066
5067         case Tabular::TABULAR_VALIGN_MIDDLE:
5068                 tabular.tabular_valignment = Tabular::LYX_VALIGN_MIDDLE;
5069                 break;
5070
5071         case Tabular::TABULAR_VALIGN_BOTTOM:
5072                 tabular.tabular_valignment = Tabular::LYX_VALIGN_BOTTOM;
5073                 break;
5074
5075         case Tabular::LONGTABULAR_ALIGN_LEFT:
5076                 tabular.longtabular_alignment = Tabular::LYX_LONGTABULAR_ALIGN_LEFT;
5077                 break;
5078
5079         case Tabular::LONGTABULAR_ALIGN_CENTER:
5080                 tabular.longtabular_alignment = Tabular::LYX_LONGTABULAR_ALIGN_CENTER;
5081                 break;
5082
5083         case Tabular::LONGTABULAR_ALIGN_RIGHT:
5084                 tabular.longtabular_alignment = Tabular::LYX_LONGTABULAR_ALIGN_RIGHT;
5085                 break;
5086
5087                 
5088
5089         case Tabular::SET_ROTATE_CELL:
5090                 for (row_type r = sel_row_start; r <= sel_row_end; ++r)
5091                         for (col_type c = sel_col_start; c <= sel_col_end; ++c)
5092                                 tabular.setRotateCell(tabular.cellIndex(r, c), true);
5093                 break;
5094
5095         case Tabular::UNSET_ROTATE_CELL:
5096                 for (row_type r = sel_row_start; r <= sel_row_end; ++r)
5097                         for (col_type c = sel_col_start; c <= sel_col_end; ++c)
5098                                 tabular.setRotateCell(tabular.cellIndex(r, c), false);
5099                 break;
5100
5101         case Tabular::TOGGLE_ROTATE_CELL:
5102                 {
5103                 bool oneNotRotated = oneCellHasRotationState(false,
5104                         sel_row_start, sel_row_end, sel_col_start, sel_col_end);
5105
5106                 for (row_type r = sel_row_start; r <= sel_row_end; ++r)
5107                         for (col_type c = sel_col_start; c <= sel_col_end; ++c)
5108                                 tabular.setRotateCell(tabular.cellIndex(r, c),
5109                                                                           oneNotRotated);
5110                 }
5111                 break;
5112
5113         case Tabular::SET_USEBOX: {
5114                 Tabular::BoxType val = Tabular::BoxType(convert<int>(value));
5115                 if (val == tabular.getUsebox(cur.idx()))
5116                         val = Tabular::BOX_NONE;
5117                 for (row_type r = sel_row_start; r <= sel_row_end; ++r)
5118                         for (col_type c = sel_col_start; c <= sel_col_end; ++c)
5119                                 tabular.setUsebox(tabular.cellIndex(r, c), val);
5120                 break;
5121         }
5122
5123         case Tabular::UNSET_LTFIRSTHEAD:
5124                 flag = false;
5125         case Tabular::SET_LTFIRSTHEAD:
5126                 tabular.getRowOfLTFirstHead(row, ltt);
5127                 checkLongtableSpecial(ltt, value, flag);
5128                 tabular.setLTHead(row, flag, ltt, true);
5129                 break;
5130
5131         case Tabular::UNSET_LTHEAD:
5132                 flag = false;
5133         case Tabular::SET_LTHEAD:
5134                 tabular.getRowOfLTHead(row, ltt);
5135                 checkLongtableSpecial(ltt, value, flag);
5136                 tabular.setLTHead(row, flag, ltt, false);
5137                 break;
5138
5139         case Tabular::UNSET_LTFOOT:
5140                 flag = false;
5141         case Tabular::SET_LTFOOT:
5142                 tabular.getRowOfLTFoot(row, ltt);
5143                 checkLongtableSpecial(ltt, value, flag);
5144                 tabular.setLTFoot(row, flag, ltt, false);
5145                 break;
5146
5147         case Tabular::UNSET_LTLASTFOOT:
5148                 flag = false;
5149         case Tabular::SET_LTLASTFOOT:
5150                 tabular.getRowOfLTLastFoot(row, ltt);
5151                 checkLongtableSpecial(ltt, value, flag);
5152                 tabular.setLTFoot(row, flag, ltt, true);
5153                 break;
5154
5155         case Tabular::SET_LTNEWPAGE:
5156                 tabular.setLTNewPage(row, !tabular.getLTNewPage(row));
5157                 break;
5158
5159         case Tabular::TOGGLE_LTCAPTION: {
5160                 bool const set = !tabular.ltCaption(row);
5161                 cur.idx() = tabular.setLTCaption(row, set);
5162                 cur.pit() = 0;
5163                 cur.pos() = 0;
5164                 cur.setSelection(false);
5165
5166                 if (set) {
5167                         // When a row is set as caption, then also insert
5168                         // a caption. Otherwise the LaTeX output is broken.
5169                         lyx::dispatch(FuncRequest(LFUN_INSET_SELECT_ALL));
5170                         lyx::dispatch(FuncRequest(LFUN_CAPTION_INSERT));
5171                 } else {
5172                         FuncRequest fr(LFUN_INSET_DISSOLVE, "caption");
5173                         if (lyx::getStatus(fr).enabled())
5174                                 lyx::dispatch(fr);
5175                 }
5176                 break;
5177         }
5178
5179         case Tabular::SET_BOOKTABS:
5180                 tabular.use_booktabs = true;
5181                 break;
5182
5183         case Tabular::UNSET_BOOKTABS:
5184                 tabular.use_booktabs = false;
5185                 break;
5186
5187         case Tabular::SET_TOP_SPACE: {
5188                 Length len;
5189                 if (value == "default")
5190                         for (row_type r = sel_row_start; r <= sel_row_end; ++r)
5191                                 tabular.row_info[r].top_space_default = true;
5192                 else if (value == "none")
5193                         for (row_type r = sel_row_start; r <= sel_row_end; ++r) {
5194                                 tabular.row_info[r].top_space_default = false;
5195                                 tabular.row_info[r].top_space = len;
5196                         }
5197                 else if (isValidLength(value, &len))
5198                         for (row_type r = sel_row_start; r <= sel_row_end; ++r) {
5199                                 tabular.row_info[r].top_space_default = false;
5200                                 tabular.row_info[r].top_space = len;
5201                         }
5202                 break;
5203         }
5204
5205         case Tabular::SET_BOTTOM_SPACE: {
5206                 Length len;
5207                 if (value == "default")
5208                         for (row_type r = sel_row_start; r <= sel_row_end; ++r)
5209                                 tabular.row_info[r].bottom_space_default = true;
5210                 else if (value == "none")
5211                         for (row_type r = sel_row_start; r <= sel_row_end; ++r) {
5212                                 tabular.row_info[r].bottom_space_default = false;
5213                                 tabular.row_info[r].bottom_space = len;
5214                         }
5215                 else if (isValidLength(value, &len))
5216                         for (row_type r = sel_row_start; r <= sel_row_end; ++r) {
5217                                 tabular.row_info[r].bottom_space_default = false;
5218                                 tabular.row_info[r].bottom_space = len;
5219                         }
5220                 break;
5221         }
5222
5223         case Tabular::SET_INTERLINE_SPACE: {
5224                 Length len;
5225                 if (value == "default")
5226                         for (row_type r = sel_row_start; r <= sel_row_end; ++r)
5227                                 tabular.row_info[r].interline_space_default = true;
5228                 else if (value == "none")
5229                         for (row_type r = sel_row_start; r <= sel_row_end; ++r) {
5230                                 tabular.row_info[r].interline_space_default = false;
5231                                 tabular.row_info[r].interline_space = len;
5232                         }
5233                 else if (isValidLength(value, &len))
5234                         for (row_type r = sel_row_start; r <= sel_row_end; ++r) {
5235                                 tabular.row_info[r].interline_space_default = false;
5236                                 tabular.row_info[r].interline_space = len;
5237                         }
5238                 break;
5239         }
5240
5241         // dummy stuff just to avoid warnings
5242         case Tabular::LAST_ACTION:
5243                 break;
5244         }
5245 }
5246
5247
5248 bool InsetTabular::copySelection(Cursor & cur)
5249 {
5250         if (!cur.selection())
5251                 return false;
5252
5253         row_type rs, re;
5254         col_type cs, ce;
5255         getSelection(cur, rs, re, cs, ce);
5256
5257         paste_tabular.reset(new Tabular(tabular));
5258
5259         for (row_type r = 0; r < rs; ++r)
5260                 paste_tabular->deleteRow(0);
5261
5262         row_type const rows = re - rs + 1;
5263         while (paste_tabular->nrows() > rows)
5264                 paste_tabular->deleteRow(rows);
5265
5266         for (col_type c = 0; c < cs; ++c)
5267                 paste_tabular->deleteColumn(0);
5268
5269         col_type const columns = ce - cs + 1;
5270         while (paste_tabular->ncols() > columns)
5271                 paste_tabular->deleteColumn(columns);
5272
5273         paste_tabular->setBuffer(tabular.buffer());
5274
5275         odocstringstream os;
5276         OutputParams const runparams(0);
5277         paste_tabular->plaintext(os, runparams, 0, true, '\t');
5278         // Needed for the "Edit->Paste recent" menu and the system clipboard.
5279         cap::copySelection(cur, os.str());
5280
5281         // mark tabular stack dirty
5282         // FIXME: this is a workaround for bug 1919. Should be removed for 1.5,
5283         // when we (hopefully) have a one-for-all paste mechanism.
5284         // This must be called after cap::copySelection.
5285         dirtyTabularStack(true);
5286
5287         return true;
5288 }
5289
5290
5291 bool InsetTabular::pasteClipboard(Cursor & cur)
5292 {
5293         if (!paste_tabular)
5294                 return false;
5295         col_type actcol = tabular.cellColumn(cur.idx());
5296         row_type actrow = tabular.cellRow(cur.idx());
5297
5298         if (cur.selIsMultiCell()) {
5299                 row_type re;
5300                 col_type ce;
5301                 getSelection(cur, actrow, re, actcol, ce);
5302         }
5303
5304         for (row_type r1 = 0, r2 = actrow;
5305              r1 < paste_tabular->nrows() && r2 < tabular.nrows();
5306              ++r1, ++r2) {
5307                 for (col_type c1 = 0, c2 = actcol;
5308                     c1 < paste_tabular->ncols() && c2 < tabular.ncols();
5309                     ++c1, ++c2) {
5310                         if (paste_tabular->isPartOfMultiColumn(r1, c1) &&
5311                               tabular.isPartOfMultiColumn(r2, c2))
5312                                 continue;
5313                         if (paste_tabular->isPartOfMultiColumn(r1, c1)) {
5314                                 --c2;
5315                                 continue;
5316                         }
5317                         if (tabular.isPartOfMultiColumn(r2, c2)) {
5318                                 --c1;
5319                                 continue;
5320                         }
5321                         shared_ptr<InsetTableCell> inset(
5322                                 new InsetTableCell(*paste_tabular->cellInset(r1, c1)));
5323                         tabular.setCellInset(r2, c2, inset);
5324                         // FIXME?: why do we need to do this explicitly? (EL)
5325                         tabular.cellInset(r2, c2)->setBuffer(tabular.buffer());
5326
5327                         // FIXME: change tracking (MG)
5328                         inset->setChange(Change(buffer().params().trackChanges ?
5329                                                 Change::INSERTED : Change::UNCHANGED));
5330                         cur.pos() = 0;
5331                 }
5332         }
5333         return true;
5334 }
5335
5336
5337 void InsetTabular::cutSelection(Cursor & cur)
5338 {
5339         if (!cur.selection())
5340                 return;
5341
5342         row_type rs, re;
5343         col_type cs, ce;
5344         getSelection(cur, rs, re, cs, ce);
5345         for (row_type r = rs; r <= re; ++r) {
5346                 for (col_type c = cs; c <= ce; ++c) {
5347                         shared_ptr<InsetTableCell> t
5348                                 = cell(tabular.cellIndex(r, c));
5349                         if (buffer().params().trackChanges)
5350                                 // FIXME: Change tracking (MG)
5351                                 t->setChange(Change(Change::DELETED));
5352                         else
5353                                 t->clear();
5354                 }
5355         }
5356
5357         // cursor position might be invalid now
5358         if (cur.pit() > cur.lastpit())
5359                 cur.pit() = cur.lastpit();
5360         if (cur.pos() > cur.lastpos())
5361                 cur.pos() = cur.lastpos();
5362         cur.clearSelection();
5363 }
5364
5365
5366 bool InsetTabular::isRightToLeft(Cursor & cur) const
5367 {
5368         LASSERT(cur.depth() > 1, /**/);
5369         Paragraph const & parentpar = cur[cur.depth() - 2].paragraph();
5370         pos_type const parentpos = cur[cur.depth() - 2].pos();
5371         return parentpar.getFontSettings(buffer().params(),
5372                                          parentpos).language()->rightToLeft();
5373 }
5374
5375
5376 docstring InsetTabular::asString(idx_type stidx, idx_type enidx, 
5377                                  bool intoInsets)
5378 {
5379         LASSERT(stidx <= enidx, return docstring());
5380         docstring retval;
5381         col_type const col1 = tabular.cellColumn(stidx);
5382         col_type const col2 = tabular.cellColumn(enidx);
5383         row_type const row1 = tabular.cellRow(stidx);
5384         row_type const row2 = tabular.cellRow(enidx);
5385         bool first = true;
5386         for (col_type col = col1; col <= col2; col++)
5387                 for (row_type row = row1; row <= row2; row++) {
5388                         if (!first)
5389                                 retval += "\n";
5390                         else
5391                                 first = false;
5392                         retval += tabular.cellInset(row, col)->asString(intoInsets);
5393                 }
5394         return retval;
5395 }
5396
5397
5398 void InsetTabular::getSelection(Cursor & cur,
5399         row_type & rs, row_type & re, col_type & cs, col_type & ce) const
5400 {
5401         CursorSlice const & beg = cur.selBegin();
5402         CursorSlice const & end = cur.selEnd();
5403         cs = tabular.cellColumn(beg.idx());
5404         ce = tabular.cellColumn(end.idx());
5405         if (cs > ce)
5406                 swap(cs, ce);
5407
5408         rs = tabular.cellRow(beg.idx());
5409         re = tabular.cellRow(end.idx());
5410         if (rs > re)
5411                 swap(rs, re);
5412 }
5413
5414
5415 Text * InsetTabular::getText(int idx) const
5416 {
5417         return size_t(idx) < nargs() ? cell(idx)->getText(0) : 0;
5418 }
5419
5420
5421 void InsetTabular::setChange(Change const & change)
5422 {
5423         for (idx_type idx = 0; idx < nargs(); ++idx)
5424                 cell(idx)->setChange(change);
5425 }
5426
5427
5428 void InsetTabular::acceptChanges()
5429 {
5430         for (idx_type idx = 0; idx < nargs(); ++idx)
5431                 cell(idx)->acceptChanges();
5432 }
5433
5434
5435 void InsetTabular::rejectChanges()
5436 {
5437         for (idx_type idx = 0; idx < nargs(); ++idx)
5438                 cell(idx)->rejectChanges();
5439 }
5440
5441
5442 bool InsetTabular::allowParagraphCustomization(idx_type cell) const
5443 {
5444         return tabular.getPWidth(cell).zero();
5445 }
5446
5447
5448 bool InsetTabular::forcePlainLayout(idx_type cell) const
5449 {
5450         return !tabular.getPWidth(cell).zero();
5451 }
5452
5453
5454 bool InsetTabular::insertPlaintextString(BufferView & bv, docstring const & buf,
5455                                      bool usePaste)
5456 {
5457         if (buf.length() <= 0)
5458                 return true;
5459
5460         col_type cols = 1;
5461         row_type rows = 1;
5462         col_type maxCols = 1;
5463         size_t const len = buf.length();
5464         size_t p = 0;
5465
5466         while (p < len &&
5467                (p = buf.find_first_of(from_ascii("\t\n"), p)) != docstring::npos) {
5468                 switch (buf[p]) {
5469                 case '\t':
5470                         ++cols;
5471                         break;
5472                 case '\n':
5473                         if (p + 1 < len)
5474                                 ++rows;
5475                         maxCols = max(cols, maxCols);
5476                         cols = 1;
5477                         break;
5478                 }
5479                 ++p;
5480         }
5481         maxCols = max(cols, maxCols);
5482         Tabular * loctab;
5483         idx_type cell = 0;
5484         col_type ocol = 0;
5485         row_type row = 0;
5486         if (usePaste) {
5487                 paste_tabular.reset(new Tabular(buffer_, rows, maxCols));
5488                 loctab = paste_tabular.get();
5489                 cols = 0;
5490                 dirtyTabularStack(true);
5491         } else {
5492                 loctab = &tabular;
5493                 cell = bv.cursor().idx();
5494                 ocol = tabular.cellColumn(cell);
5495                 row = tabular.cellRow(cell);
5496         }
5497
5498         size_t op = 0;
5499         idx_type const cells = loctab->numberofcells;
5500         p = 0;
5501         cols = ocol;
5502         rows = loctab->nrows();
5503         col_type const columns = loctab->ncols();
5504
5505         while (cell < cells && p < len && row < rows &&
5506                (p = buf.find_first_of(from_ascii("\t\n"), p)) != docstring::npos)
5507         {
5508                 if (p >= len)
5509                         break;
5510                 switch (buf[p]) {
5511                 case '\t':
5512                         // we can only set this if we are not too far right
5513                         if (cols < columns) {
5514                                 shared_ptr<InsetTableCell> inset = loctab->cellInset(cell);
5515                                 Font const font = bv.textMetrics(&inset->text()).
5516                                         displayFont(0, 0);
5517                                 inset->setText(buf.substr(op, p - op), font,
5518                                                buffer().params().trackChanges);
5519                                 ++cols;
5520                                 ++cell;
5521                         }
5522                         break;
5523                 case '\n':
5524                         // we can only set this if we are not too far right
5525                         if (cols < columns) {
5526                                 shared_ptr<InsetTableCell> inset = tabular.cellInset(cell);
5527                                 Font const font = bv.textMetrics(&inset->text()).
5528                                         displayFont(0, 0);
5529                                 inset->setText(buf.substr(op, p - op), font,
5530                                                buffer().params().trackChanges);
5531                         }
5532                         cols = ocol;
5533                         ++row;
5534                         if (row < rows)
5535                                 cell = loctab->cellIndex(row, cols);
5536                         break;
5537                 }
5538                 ++p;
5539                 op = p;
5540         }
5541         // check for the last cell if there is no trailing '\n'
5542         if (cell < cells && op < len) {
5543                 shared_ptr<InsetTableCell> inset = loctab->cellInset(cell);
5544                 Font const font = bv.textMetrics(&inset->text()).displayFont(0, 0);
5545                 inset->setText(buf.substr(op, len - op), font,
5546                         buffer().params().trackChanges);
5547         }
5548         return true;
5549 }
5550
5551
5552 void InsetTabular::addPreview(DocIterator const & inset_pos,
5553         PreviewLoader & loader) const
5554 {
5555         DocIterator cell_pos = inset_pos;
5556
5557         cell_pos.push_back(CursorSlice(*const_cast<InsetTabular *>(this)));
5558         for (row_type r = 0; r < tabular.nrows(); ++r) {
5559                 for (col_type c = 0; c < tabular.ncols(); ++c) {
5560                         cell_pos.top().idx() = tabular.cellIndex(r, c);
5561                         tabular.cellInset(r, c)->addPreview(cell_pos, loader);
5562                 }
5563         }
5564 }
5565
5566
5567 bool InsetTabular::completionSupported(Cursor const & cur) const
5568 {
5569         Cursor const & bvCur = cur.bv().cursor();
5570         if (&bvCur.inset() != this)
5571                 return false;
5572         return cur.text()->completionSupported(cur);
5573 }
5574
5575
5576 bool InsetTabular::inlineCompletionSupported(Cursor const & cur) const
5577 {
5578         return completionSupported(cur);
5579 }
5580
5581
5582 bool InsetTabular::automaticInlineCompletion() const
5583 {
5584         return lyxrc.completion_inline_text;
5585 }
5586
5587
5588 bool InsetTabular::automaticPopupCompletion() const
5589 {
5590         return lyxrc.completion_popup_text;
5591 }
5592
5593
5594 bool InsetTabular::showCompletionCursor() const
5595 {
5596         return lyxrc.completion_cursor_text;
5597 }
5598
5599
5600 CompletionList const * InsetTabular::createCompletionList(Cursor const & cur) const
5601 {
5602         return completionSupported(cur) ? cur.text()->createCompletionList(cur) : 0;
5603 }
5604
5605
5606 docstring InsetTabular::completionPrefix(Cursor const & cur) const
5607 {
5608         if (!completionSupported(cur))
5609                 return docstring();
5610         return cur.text()->completionPrefix(cur);
5611 }
5612
5613
5614 bool InsetTabular::insertCompletion(Cursor & cur, docstring const & s, bool finished)
5615 {
5616         if (!completionSupported(cur))
5617                 return false;
5618
5619         return cur.text()->insertCompletion(cur, s, finished);
5620 }
5621
5622
5623 void InsetTabular::completionPosAndDim(Cursor const & cur, int & x, int & y, 
5624                                     Dimension & dim) const
5625 {
5626         TextMetrics const & tm = cur.bv().textMetrics(cur.text());
5627         tm.completionPosAndDim(cur, x, y, dim);
5628 }
5629
5630
5631 void InsetTabular::string2params(string const & in, InsetTabular & inset)
5632 {
5633         istringstream data(in);
5634         Lexer lex;
5635         lex.setStream(data);
5636
5637         if (in.empty())
5638                 return;
5639
5640         string token;
5641         lex >> token;
5642         if (!lex || token != "tabular") {
5643                 LYXERR0("Expected arg 1 to be \"tabular\" in " << in);
5644                 return;
5645         }
5646
5647         // This is part of the inset proper that is usually swallowed
5648         // by Buffer::readInset
5649         lex >> token;
5650         if (!lex || token != "Tabular") {
5651                 LYXERR0("Expected arg 2 to be \"Tabular\" in " << in);
5652                 return;
5653         }
5654
5655         inset.read(lex);
5656 }
5657
5658
5659 string InsetTabular::params2string(InsetTabular const & inset)
5660 {
5661         ostringstream data;
5662         data << "tabular" << ' ';
5663         inset.write(data);
5664         data << "\\end_inset\n";
5665         return data.str();
5666 }
5667
5668
5669 } // namespace lyx