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