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