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