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