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