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