]> git.lyx.org Git - lyx.git/blob - src/insets/InsetTabular.cpp
simplify some conditions
[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));
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) {
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.getAlignment(cell) == LYX_ALIGN_DECIMAL) {
3366                                 // make a copy which we will split in 2
3367                                 InsetTableCell head = InsetTableCell(*tabular.cellInset(cell).get());
3368                                 head.getText(0)->setMacrocontextPosition(
3369                                         tabular.cellInset(cell)->getText(0)->macrocontextPosition());
3370                                 head.setBuffer(tabular.buffer());
3371                                 // split in 2 and calculate width of each part
3372                                 bool hassep = false;
3373                                 InsetTableCell tail = 
3374                                         splitCell(head, tabular.column_info[c].decimal_point, hassep);
3375                                 Dimension dim1;
3376                                 head.metrics(m, dim1);
3377                                 decimal_hoffset = dim1.width();
3378                                 if (hassep) {
3379                                         tail.metrics(m, dim1);
3380                                         decimal_width = dim1.width();
3381                                 }
3382                         }
3383                         tabular.cell_info[r][c].decimal_hoffset = decimal_hoffset;
3384                         tabular.cell_info[r][c].decimal_width = decimal_width;
3385
3386                         // with LYX_VALIGN_BOTTOM the descent is relative to the last par
3387                         // = descent of text in last par + TEXT_TO_INSET_OFFSET:
3388                         int const lastpardes = tm.last().second->descent()
3389                                 + TEXT_TO_INSET_OFFSET;
3390                         int offset = 0;
3391                         switch (tabular.getVAlignment(cell)) { 
3392                                 case Tabular::LYX_VALIGN_TOP:
3393                                         break; 
3394                                 case Tabular::LYX_VALIGN_MIDDLE:
3395                                         offset = -(dim.des - lastpardes)/2; 
3396                                         break; 
3397                                 case Tabular::LYX_VALIGN_BOTTOM:
3398                                         offset = -(dim.des - lastpardes); 
3399                                         break;
3400                         }
3401                         tabular.cell_info[r][c].voffset = offset;
3402                         maxasc = max(maxasc, dim.asc - offset);
3403                         maxdes = max(maxdes, dim.des + offset);
3404                 }
3405                 int const top_space = tabular.row_info[r].top_space_default ?
3406                         default_line_space :
3407                         tabular.row_info[r].top_space.inPixels(mi.base.textwidth);
3408                 tabular.setRowAscent(r, maxasc + ADD_TO_HEIGHT + top_space);
3409                 int const bottom_space = tabular.row_info[r].bottom_space_default ?
3410                         default_line_space :
3411                         tabular.row_info[r].bottom_space.inPixels(mi.base.textwidth);
3412                 tabular.setRowDescent(r, maxdes + ADD_TO_HEIGHT + bottom_space);
3413         }
3414         tabular.updateColumnWidths();
3415         dim.asc = tabular.rowAscent(0);
3416         dim.des = tabular.height() - dim.asc;
3417         dim.wid = tabular.width() + 2 * ADD_TO_TABULAR_WIDTH;
3418 }
3419
3420
3421 bool InsetTabular::isCellSelected(Cursor & cur, row_type row, col_type col) 
3422         const
3423 {
3424         if (&cur.inset() == this && cur.selection()) {
3425                 if (cur.selIsMultiCell()) {
3426                         row_type rs, re;
3427                         col_type cs, ce;
3428                         getSelection(cur, rs, re, cs, ce);
3429                         
3430                         idx_type const cell = tabular.cellIndex(row, col);
3431                         col_type const cspan = tabular.columnSpan(cell);
3432                         row_type const rspan = tabular.rowSpan(cell);
3433                         if (col + cspan - 1 >= cs && col <= ce 
3434                                 && row + rspan - 1 >= rs && row <= re)
3435                                 return true;
3436                 } else 
3437                         if (col == tabular.cellColumn(cur.idx()) 
3438                                 && row == tabular.cellRow(cur.idx())) {
3439                         CursorSlice const & beg = cur.selBegin();
3440                         CursorSlice const & end = cur.selEnd();
3441
3442                         if ((end.lastpos() > 0 || end.lastpit() > 0)
3443                                   && end.pos() == end.lastpos() && beg.pos() == 0
3444                                   && end.pit() == end.lastpit() && beg.pit() == 0)
3445                                 return true;
3446                 }
3447         }
3448         return false;
3449 }
3450
3451
3452 void InsetTabular::draw(PainterInfo & pi, int x, int y) const
3453 {
3454         x += scx_ + ADD_TO_TABULAR_WIDTH;
3455
3456         BufferView * bv = pi.base.bv;
3457         Cursor & cur = pi.base.bv->cursor();
3458         resetPos(cur);
3459
3460         // FIXME: As the full background is painted in drawSelection(),
3461         // we have no choice but to do a full repaint for the Text cells.
3462         pi.full_repaint = true;
3463
3464         bool const original_selection_state = pi.selected;
3465
3466         idx_type idx = 0;
3467         first_visible_cell = Tabular::npos;
3468         for (row_type r = 0; r < tabular.nrows(); ++r) {
3469                 int nx = x;
3470                 for (col_type c = 0; c < tabular.ncols(); ++c) {
3471                         if (tabular.isPartOfMultiColumn(r, c))
3472                                 continue;
3473                         
3474                         idx = tabular.cellIndex(r, c);
3475                         
3476                         if (tabular.isPartOfMultiRow(r, c)) {
3477                                 nx += tabular.columnWidth(idx);
3478                                 continue;
3479                         }
3480
3481                         if (first_visible_cell == Tabular::npos)
3482                                 first_visible_cell = idx;
3483
3484                         pi.selected |= isCellSelected(cur, r, c);
3485                         int const cx = nx + tabular.textHOffset(idx);
3486                         int const cy = y  + tabular.textVOffset(idx);
3487                         // Cache the Inset position.
3488                         bv->coordCache().insets().add(cell(idx).get(), cx, cy);
3489                         cell(idx)->draw(pi, cx, cy);
3490                         drawCellLines(pi.pain, nx, y, r, idx, pi.change_);
3491                         nx += tabular.columnWidth(idx);
3492                         pi.selected = original_selection_state;
3493                 }
3494
3495                 if (r + 1 < tabular.nrows())
3496                         y += tabular.rowDescent(r) + tabular.rowAscent(r + 1) 
3497                                 + tabular.interRowSpace(r + 1);
3498         }
3499 }
3500
3501
3502 void InsetTabular::drawSelection(PainterInfo & pi, int x, int y) const
3503 {
3504         Cursor & cur = pi.base.bv->cursor();
3505         resetPos(cur);
3506
3507         x += scx_ + ADD_TO_TABULAR_WIDTH;
3508
3509         // FIXME: it is wrong to completely paint the background
3510         // if we want to do single row painting.
3511
3512         // Paint background of current tabular
3513         int const w = tabular.width();
3514         int const h = tabular.height();
3515         int yy = y - tabular.rowAscent(0);
3516         pi.pain.fillRectangle(x, yy, w, h, pi.backgroundColor(this));
3517
3518         if (!cur.selection())
3519                 return;
3520         if (&cur.inset() != this)
3521                 return;
3522
3523         //resetPos(cur);
3524
3525         bool const full_cell_selected = isCellSelected(cur,
3526                 tabular.cellRow(cur.idx()), tabular.cellColumn(cur.idx()));
3527
3528         if (cur.selIsMultiCell() || full_cell_selected) {
3529                 for (row_type r = 0; r < tabular.nrows(); ++r) {
3530                         int xx = x;
3531                         for (col_type c = 0; c < tabular.ncols(); ++c) {
3532                                 if (tabular.isPartOfMultiColumn(r, c))
3533                                         continue;
3534
3535                                 idx_type const cell = tabular.cellIndex(r, c);
3536
3537                                 if (tabular.isPartOfMultiRow(r, c)) {
3538                                         xx += tabular.columnWidth(cell);
3539                                         continue;
3540                                 }
3541                                 int const w = tabular.columnWidth(cell);
3542                                 int const h = tabular.cellHeight(cell);
3543                                 int const yy = y - tabular.rowAscent(r);
3544                                 if (isCellSelected(cur, r, c))
3545                                         pi.pain.fillRectangle(xx, yy, w, h, Color_selection);
3546                                 xx += w;
3547                         }
3548                         if (r + 1 < tabular.nrows())
3549                                 y += tabular.rowDescent(r) + tabular.rowAscent(r + 1)
3550                                      + tabular.interRowSpace(r + 1);
3551                 }
3552
3553         } else {
3554                 x += cellXPos(cur.idx());
3555                 x += tabular.textHOffset(cur.idx());
3556                 cell(cur.idx())->drawSelection(pi, x, 0 /* ignored */);
3557         }
3558 }
3559
3560
3561 void InsetTabular::drawCellLines(Painter & pain, int x, int y,
3562                                                                  row_type row, idx_type cell, Change const & change) const
3563 {
3564         y -= tabular.rowAscent(row);
3565         int const w = tabular.columnWidth(cell);
3566         int const h = tabular.cellHeight(cell);
3567         Color linecolor = change.changed() ? change.color() : Color_tabularline;
3568         Color gridcolor = change.changed() ? change.color() : Color_tabularonoffline;
3569
3570         // Top
3571         bool drawline = tabular.topLine(cell)
3572                 || (row > 0 && tabular.bottomLine(tabular.cellAbove(cell)));
3573         pain.line(x, y, x + w, y,
3574                 drawline ? linecolor : gridcolor,
3575                 drawline ? Painter::line_solid : Painter::line_onoffdash);
3576
3577         // Bottom
3578         drawline = tabular.bottomLine(cell);
3579         pain.line(x, y + h, x + w, y + h,
3580                 drawline ? linecolor : gridcolor,
3581                 drawline ? Painter::line_solid : Painter::line_onoffdash);
3582
3583         // Left
3584         col_type const col = tabular.cellColumn(cell);
3585         drawline = tabular.leftLine(cell)
3586                 || (col > 0 && tabular.rightLine(tabular.cellIndex(row, col - 1)));
3587         pain.line(x, y, x, y + h,
3588                 drawline ? linecolor : gridcolor,
3589                 drawline ? Painter::line_solid : Painter::line_onoffdash);
3590
3591         // Right
3592         x -= tabular.interColumnSpace(cell);
3593         drawline = tabular.rightLine(cell)
3594                    || (col + 1 < tabular.ncols()
3595                        && tabular.leftLine(tabular.cellIndex(row, col + 1)));
3596         pain.line(x + w, y, x + w, y + h,
3597                 drawline ? linecolor : gridcolor,
3598                 drawline ? Painter::line_solid : Painter::line_onoffdash);
3599 }
3600
3601
3602 void InsetTabular::edit(Cursor & cur, bool front, EntryDirection)
3603 {
3604         //lyxerr << "InsetTabular::edit: " << this << endl;
3605         cur.finishUndo();
3606         cur.setSelection(false);
3607         cur.push(*this);
3608         if (front) {
3609                 if (isRightToLeft(cur))
3610                         cur.idx() = tabular.getLastCellInRow(0);
3611                 else
3612                         cur.idx() = 0;
3613                 cur.pit() = 0;
3614                 cur.pos() = 0;
3615         } else {
3616                 if (isRightToLeft(cur))
3617                         cur.idx() = tabular.getFirstCellInRow(tabular.nrows() - 1);
3618                 else
3619                         cur.idx() = tabular.numberofcells - 1;
3620                 cur.pit() = 0;
3621                 cur.pos() = cur.lastpos(); // FIXME crude guess
3622         }
3623         cur.setCurrentFont();
3624         // FIXME: this accesses the position cache before it is initialized
3625         //resetPos(cur);
3626         //cur.bv().fitCursor();
3627 }
3628
3629
3630 void InsetTabular::updateBuffer(ParIterator const & it, UpdateType utype)
3631 {
3632         // In a longtable, tell captions what the current float is
3633         Counters & cnts = buffer().masterBuffer()->params().documentClass().counters();
3634         string const saveflt = cnts.current_float();
3635         if (tabular.is_long_tabular)
3636                 cnts.current_float("table");
3637
3638         ParIterator it2 = it;
3639         it2.forwardPos();
3640         size_t const end = it2.nargs();
3641         for ( ; it2.idx() < end; it2.top().forwardIdx())
3642                 buffer().updateBuffer(it2, utype);
3643
3644         //reset afterwards
3645         if (tabular.is_long_tabular)
3646                 cnts.current_float(saveflt);
3647 }
3648
3649
3650 void InsetTabular::addToToc(DocIterator const & cpit)
3651 {
3652         DocIterator dit = cpit;
3653         dit.forwardPos();
3654         size_t const end = dit.nargs();
3655         for ( ; dit.idx() < end; dit.top().forwardIdx())
3656                 cell(dit.idx())->addToToc(dit);
3657 }
3658
3659
3660 void InsetTabular::doDispatch(Cursor & cur, FuncRequest & cmd)
3661 {
3662         LYXERR(Debug::DEBUG, "# InsetTabular::doDispatch: cmd: " << cmd
3663                              << "\n  cur:" << cur);
3664         CursorSlice sl = cur.top();
3665         Cursor & bvcur = cur.bv().cursor();
3666
3667         FuncCode const act = cmd.action();
3668         
3669         switch (act) {
3670
3671         case LFUN_MOUSE_PRESS: {
3672                 //lyxerr << "# InsetTabular::MousePress\n" << cur.bv().cursor() << endl;
3673                 // select row
3674                 if (cmd.x() < xo(cur.bv()) + ADD_TO_TABULAR_WIDTH
3675                         || cmd.x() > xo(cur.bv()) + tabular.width()) {
3676                         row_type r = rowFromY(cur, cmd.y());
3677                         cur.idx() = tabular.getFirstCellInRow(r);
3678                         cur.pos() = 0;
3679                         cur.resetAnchor();
3680                         cur.idx() = tabular.getLastCellInRow(r);
3681                         cur.pos() = cur.lastpos();
3682                         cur.setSelection(true);
3683                         bvcur = cur; 
3684                         rowselect_ = true;
3685                         break;
3686                 }
3687                 // select column
3688                 int const y0 = yo(cur.bv()) - tabular.rowAscent(0);
3689                 if (cmd.y() < y0 + ADD_TO_TABULAR_WIDTH 
3690                         || cmd.y() > y0 + tabular.height()) {
3691                         col_type c = columnFromX(cur, cmd.x());
3692                         cur.idx() = tabular.cellIndex(0, c);
3693                         cur.pos() = 0;
3694                         cur.resetAnchor();
3695                         cur.idx() = tabular.cellIndex(tabular.nrows() - 1, c);
3696                         cur.pos() = cur.lastpos();
3697                         cur.setSelection(true);
3698                         bvcur = cur; 
3699                         colselect_ = true;
3700                         break;
3701                 }
3702                 // do not reset cursor/selection if we have selected
3703                 // some cells (bug 2715).
3704                 if (cmd.button() == mouse_button::button3
3705                     && &bvcur.selBegin().inset() == this 
3706                     && bvcur.selIsMultiCell()) 
3707                         ;
3708                 else
3709                         // Let InsetTableCell do it
3710                         cell(cur.idx())->dispatch(cur, cmd);
3711                 break;
3712         }
3713         case LFUN_MOUSE_MOTION:
3714                 //lyxerr << "# InsetTabular::MouseMotion\n" << bvcur << endl;
3715                 if (cmd.button() == mouse_button::button1) {
3716                         // only accept motions to places not deeper nested than the real anchor
3717                         if (!bvcur.realAnchor().hasPart(cur)) {
3718                                 cur.undispatched();
3719                                 break;
3720                         }
3721                         // select (additional) row
3722                         if (rowselect_) {
3723                                 row_type r = rowFromY(cur, cmd.y());
3724                                 cur.idx() = tabular.getLastCellInRow(r);
3725                                 // we need to reset the cursor's pit and pos now, as the old ones
3726                                 // may no longer be valid.
3727                                 cur.pit() = 0;
3728                                 cur.pos() = 0;
3729                                 bvcur.setCursor(cur);
3730                                 bvcur.setSelection(true);
3731                                 break;
3732                         }
3733                         // select (additional) column
3734                         if (colselect_) {
3735                                 col_type c = columnFromX(cur, cmd.x());
3736                                 cur.idx() = tabular.cellIndex(tabular.nrows() - 1, c);
3737                                 // we need to reset the cursor's pit and pos now, as the old ones
3738                                 // may no longer be valid.
3739                                 cur.pit() = 0;
3740                                 cur.pos() = 0;
3741                                 bvcur.setCursor(cur);
3742                                 bvcur.setSelection(true);
3743                                 break;
3744                         }
3745                         // only update if selection changes
3746                         if (bvcur.idx() == cur.idx() &&
3747                                 !(bvcur.realAnchor().idx() == cur.idx() && bvcur.pos() != cur.pos()))
3748                                 cur.noUpdate();
3749                         setCursorFromCoordinates(cur, cmd.x(), cmd.y());
3750                         bvcur.setCursor(cur);
3751                         bvcur.setSelection(true);
3752                         // if this is a multicell selection, we just set the cursor to
3753                         // the beginning of the cell's text.
3754                         if (bvcur.selIsMultiCell()) {
3755                                 bvcur.pit() = bvcur.lastpit();
3756                                 bvcur.pos() = bvcur.lastpos();
3757                         }
3758                 }
3759                 break;
3760
3761         case LFUN_MOUSE_RELEASE:
3762                 rowselect_ = false;
3763                 colselect_ = false;
3764                 break;
3765
3766         case LFUN_CELL_BACKWARD:
3767                 movePrevCell(cur);
3768                 cur.setSelection(false);
3769                 break;
3770
3771         case LFUN_CELL_FORWARD:
3772                 moveNextCell(cur);
3773                 cur.setSelection(false);
3774                 break;
3775
3776         case LFUN_CHAR_FORWARD_SELECT:
3777         case LFUN_CHAR_FORWARD:
3778         case LFUN_CHAR_BACKWARD_SELECT:
3779         case LFUN_CHAR_BACKWARD:
3780         case LFUN_CHAR_RIGHT_SELECT:
3781         case LFUN_CHAR_RIGHT:
3782         case LFUN_CHAR_LEFT_SELECT:
3783         case LFUN_CHAR_LEFT: {
3784                 // determine whether we move to next or previous cell, where to enter 
3785                 // the new cell from, and which command to "finish" (i.e., exit the
3786                 // inset) with:
3787                 bool next_cell;
3788                 EntryDirection entry_from = ENTRY_DIRECTION_IGNORE;
3789                 FuncCode finish_lfun;
3790
3791                 if (act == LFUN_CHAR_FORWARD 
3792                                 || act == LFUN_CHAR_FORWARD_SELECT) {
3793                         next_cell = true;
3794                         finish_lfun = LFUN_FINISHED_FORWARD;
3795                 }
3796                 else if (act == LFUN_CHAR_BACKWARD
3797                                 || act == LFUN_CHAR_BACKWARD_SELECT) {
3798                         next_cell = false;
3799                         finish_lfun = LFUN_FINISHED_BACKWARD;
3800                 }
3801                 // LEFT or RIGHT commands --- the interpretation will depend on the 
3802                 // table's direction.
3803                 else {
3804                         bool const right = act == LFUN_CHAR_RIGHT
3805                                 || act == LFUN_CHAR_RIGHT_SELECT;
3806                         next_cell = isRightToLeft(cur) != right;
3807                         
3808                         if (lyxrc.visual_cursor)
3809                                 entry_from = right ? ENTRY_DIRECTION_LEFT:ENTRY_DIRECTION_RIGHT;
3810
3811                         finish_lfun = right ? LFUN_FINISHED_RIGHT : LFUN_FINISHED_LEFT;
3812                 }
3813
3814                 bool const select = act == LFUN_CHAR_FORWARD_SELECT ||
3815                     act == LFUN_CHAR_BACKWARD_SELECT ||
3816                     act == LFUN_CHAR_RIGHT_SELECT ||
3817                     act == LFUN_CHAR_LEFT_SELECT;
3818
3819                 // If we have a multicell selection or we're 
3820                 // not doing some LFUN_*_SELECT thing anyway...
3821                 if (!cur.selIsMultiCell() || !select) {
3822                         col_type const c = tabular.cellColumn(cur.idx());
3823                         row_type const r = tabular.cellRow(cur.idx());
3824                         // Are we trying to select the whole cell and is the whole cell 
3825                         // not yet selected?
3826                         bool const select_whole = select && !isCellSelected(cur, r, c) &&
3827                                 ((next_cell && cur.pit() == cur.lastpit() 
3828                                 && cur.pos() == cur.lastpos())
3829                                 || (!next_cell && cur.pit() == 0 && cur.pos() == 0));
3830
3831                         bool const empty_cell = cur.lastpos() == 0 && cur.lastpit() == 0;
3832
3833                         // ...try to dispatch to the cell's inset.
3834                         cell(cur.idx())->dispatch(cur, cmd);
3835
3836                         // When we already have a selection we want to select the whole cell
3837                         // before going to the next cell.
3838                         if (select_whole && !empty_cell){
3839                                 getText(cur.idx())->selectAll(cur);
3840                                 cur.dispatched();
3841                                 break;
3842                         }
3843
3844                         // FIXME: When we support the selection of an empty cell, remove 
3845                         // the !empty_cell from this condition. For now we jump to the next
3846                         // cell if the current cell is empty.
3847                         if (cur.result().dispatched() && !empty_cell)
3848                                 break;
3849                 }
3850
3851                 // move to next/prev cell, as appropriate
3852                 // note that we will always do this if we're selecting and we have
3853                 // a multicell selection
3854                 LYXERR(Debug::RTL, "entering " << (next_cell ? "next" : "previous")
3855                         << " cell from: " << int(entry_from));
3856                 if (next_cell)
3857                         moveNextCell(cur, entry_from);
3858                 else
3859                         movePrevCell(cur, entry_from);
3860                 // if we're exiting the table, call the appropriate FINISHED lfun
3861                 if (sl == cur.top())
3862                         cmd = FuncRequest(finish_lfun);
3863                 else
3864                         cur.dispatched();
3865                 break;
3866
3867         }
3868
3869         case LFUN_DOWN_SELECT:
3870         case LFUN_DOWN:
3871                 if (!(cur.selection() && cur.selIsMultiCell()))
3872                         cell(cur.idx())->dispatch(cur, cmd);
3873                 
3874                 cur.dispatched(); // override the cell's decision
3875                 if (sl == cur.top()) {
3876                         // if our Text didn't do anything to the cursor
3877                         // then we try to put the cursor into the cell below
3878                         // setting also the right targetX.
3879                         cur.selHandle(act == LFUN_DOWN_SELECT);
3880                         if (tabular.cellRow(cur.idx()) != tabular.nrows() - 1) {
3881                                 cur.idx() = tabular.cellBelow(cur.idx());
3882                                 cur.pit() = 0;
3883                                 TextMetrics const & tm =
3884                                         cur.bv().textMetrics(cell(cur.idx())->getText(0));
3885                                 cur.pos() = tm.x2pos(cur.pit(), 0, cur.targetX());
3886                                 cur.setCurrentFont();
3887                         }
3888                 }
3889                 if (sl == cur.top()) {
3890                         // we trick it to go to forward after leaving the
3891                         // tabular.
3892                         cmd = FuncRequest(LFUN_FINISHED_FORWARD);
3893                         cur.undispatched();
3894                 }
3895                 if (cur.selIsMultiCell()) {
3896                         cur.pit() = cur.lastpit();
3897                         cur.pos() = cur.lastpos();
3898                         cur.setCurrentFont();
3899                         return;
3900                 }
3901                 break;
3902
3903         case LFUN_UP_SELECT:
3904         case LFUN_UP:
3905                 if (!(cur.selection() && cur.selIsMultiCell()))
3906                         cell(cur.idx())->dispatch(cur, cmd);
3907                 cur.dispatched(); // override the cell's decision
3908                 if (sl == cur.top()) {
3909                         // if our Text didn't do anything to the cursor
3910                         // then we try to put the cursor into the cell above
3911                         // setting also the right targetX.
3912                         cur.selHandle(act == LFUN_UP_SELECT);
3913                         if (tabular.cellRow(cur.idx()) != 0) {
3914                                 cur.idx() = tabular.cellAbove(cur.idx());
3915                                 cur.pit() = cur.lastpit();
3916                                 Text const * text = cell(cur.idx())->getText(0);
3917                                 TextMetrics const & tm = cur.bv().textMetrics(text);
3918                                 ParagraphMetrics const & pm =
3919                                         tm.parMetrics(cur.lastpit());
3920                                 cur.pos() = tm.x2pos(cur.pit(), pm.rows().size()-1, cur.targetX());
3921                                 cur.setCurrentFont();
3922                         }
3923                 }
3924                 if (sl == cur.top()) {
3925                         cmd = FuncRequest(LFUN_UP);
3926                         cur.undispatched();
3927                 }
3928                 if (cur.selIsMultiCell()) {
3929                         cur.pit() = 0;
3930                         cur.pos() = cur.lastpos();
3931                         cur.setCurrentFont();
3932                         return;
3933                 }
3934                 break;
3935
3936 //      case LFUN_SCREEN_DOWN: {
3937 //              //if (hasSelection())
3938 //              //      cur.selection() = false;
3939 //              col_type const col = tabular.cellColumn(cur.idx());
3940 //              int const t =   cur.bv().top_y() + cur.bv().height();
3941 //              if (t < yo() + tabular.getHeightOfTabular()) {
3942 //                      cur.bv().scrollDocView(t);
3943 //                      cur.idx() = tabular.cellBelow(first_visible_cell) + col;
3944 //              } else {
3945 //                      cur.idx() = tabular.getFirstCellInRow(tabular.rows() - 1) + col;
3946 //              }
3947 //              cur.par() = 0;
3948 //              cur.pos() = 0;
3949 //              break;
3950 //      }
3951 //
3952 //      case LFUN_SCREEN_UP: {
3953 //              //if (hasSelection())
3954 //              //      cur.selection() = false;
3955 //              col_type const col = tabular.cellColumn(cur.idx());
3956 //              int const t =   cur.bv().top_y() + cur.bv().height();
3957 //              if (yo() < 0) {
3958 //                      cur.bv().scrollDocView(t);
3959 //                      if (yo() > 0)
3960 //                              cur.idx() = col;
3961 //                      else
3962 //                              cur.idx() = tabular.cellBelow(first_visible_cell) + col;
3963 //              } else {
3964 //                      cur.idx() = col;
3965 //              }
3966 //              cur.par() = cur.lastpar();
3967 //              cur.pos() = cur.lastpos();
3968 //              break;
3969 //      }
3970
3971         case LFUN_LAYOUT_TABULAR:
3972                 cur.bv().showDialog("tabular");
3973                 break;
3974
3975         case LFUN_INSET_MODIFY:
3976                 if (!tabularFeatures(cur, to_utf8(cmd.argument())))
3977                         cur.undispatched();
3978                 break;
3979
3980         // insert file functions
3981         case LFUN_FILE_INSERT_PLAINTEXT_PARA:
3982         case LFUN_FILE_INSERT_PLAINTEXT:
3983                 // FIXME UNICODE
3984                 if (FileName::isAbsolute(to_utf8(cmd.argument()))) {
3985                         docstring const tmpstr = cur.bv().contentsOfPlaintextFile(
3986                                 FileName(to_utf8(cmd.argument())));
3987                         if (tmpstr.empty())
3988                                 break;
3989                         cur.recordUndoInset(INSERT_UNDO);
3990                         if (insertPlaintextString(cur.bv(), tmpstr, false)) {
3991                                 // content has been replaced,
3992                                 // so cursor might be invalid
3993                                 cur.pos() = cur.lastpos();
3994                                 cur.pit() = cur.lastpit();
3995                                 bvcur.setCursor(cur);
3996                         } else
3997                                 cur.undispatched();
3998                 }
3999                 break;
4000
4001         case LFUN_CUT:
4002                 if (cur.selIsMultiCell()) {
4003                         if (copySelection(cur)) {
4004                                 cur.recordUndoInset(DELETE_UNDO);
4005                                 cutSelection(cur);
4006                         }
4007                 } else
4008                         cell(cur.idx())->dispatch(cur, cmd);
4009                 break;
4010
4011         case LFUN_SELF_INSERT:
4012                 if (cur.selIsMultiCell()) {
4013                         cur.recordUndoInset(DELETE_UNDO);
4014                         cutSelection(cur);
4015                 }
4016                 cell(cur.idx())->dispatch(cur, cmd);
4017                 break;
4018
4019         case LFUN_CHAR_DELETE_BACKWARD:
4020         case LFUN_CHAR_DELETE_FORWARD:
4021                 if (cur.selIsMultiCell()) {
4022                         cur.recordUndoInset(DELETE_UNDO);
4023                         cutSelection(cur);
4024                 } else
4025                         cell(cur.idx())->dispatch(cur, cmd);
4026                 break;
4027
4028         case LFUN_COPY:
4029                 if (!cur.selection())
4030                         break;
4031                 if (cur.selIsMultiCell()) {
4032                         cur.finishUndo();
4033                         copySelection(cur);
4034                 } else
4035                         cell(cur.idx())->dispatch(cur, cmd);
4036                 break;
4037
4038         case LFUN_CLIPBOARD_PASTE:
4039         case LFUN_PRIMARY_SELECTION_PASTE: {
4040                 docstring const clip = (act == LFUN_CLIPBOARD_PASTE) ?
4041                         theClipboard().getAsText() :
4042                         theSelection().get();
4043                 if (clip.empty())
4044                         break;
4045                 // pass to InsertPlaintextString, but
4046                 // only if we have multi-cell content
4047                 if (clip.find_first_of(from_ascii("\t\n")) != docstring::npos) {
4048                         cur.recordUndoInset(INSERT_UNDO);
4049                         if (insertPlaintextString(cur.bv(), clip, false)) {
4050                                 // content has been replaced,
4051                                 // so cursor might be invalid
4052                                 cur.pos() = cur.lastpos();
4053                                 cur.pit() = cur.lastpit();
4054                                 bvcur.setCursor(cur);
4055                                 break;
4056                         }
4057                 }
4058                 // Let the cell handle normal text
4059                 cell(cur.idx())->dispatch(cur, cmd);
4060                 break;
4061         }
4062
4063         case LFUN_PASTE:
4064                 if (!tabularStackDirty()) {
4065                         if (!cur.selIsMultiCell())
4066                                 cell(cur.idx())->dispatch(cur, cmd);
4067                         break;
4068                 }
4069                 if (theClipboard().isInternal() ||
4070                     (!theClipboard().hasInternal() && theClipboard().hasLyXContents())) {
4071                         cur.recordUndoInset(INSERT_UNDO);
4072                         pasteClipboard(cur);
4073                 }
4074                 break;
4075
4076         case LFUN_FONT_EMPH:
4077         case LFUN_FONT_BOLD:
4078         case LFUN_FONT_BOLDSYMBOL:
4079         case LFUN_FONT_ROMAN:
4080         case LFUN_FONT_NOUN:
4081         case LFUN_FONT_ITAL:
4082         case LFUN_FONT_FRAK:
4083         case LFUN_FONT_TYPEWRITER:
4084         case LFUN_FONT_SANS:
4085         case LFUN_TEXTSTYLE_APPLY:
4086         case LFUN_TEXTSTYLE_UPDATE:
4087         case LFUN_FONT_SIZE:
4088         case LFUN_FONT_UNDERLINE:
4089         case LFUN_FONT_STRIKEOUT:
4090         case LFUN_FONT_UULINE:
4091         case LFUN_FONT_UWAVE:
4092         case LFUN_LANGUAGE:
4093         case LFUN_WORD_CAPITALIZE:
4094         case LFUN_WORD_UPCASE:
4095         case LFUN_WORD_LOWCASE:
4096         case LFUN_CHARS_TRANSPOSE:
4097                 if (cur.selIsMultiCell()) {
4098                         row_type rs, re;
4099                         col_type cs, ce;
4100                         getSelection(cur, rs, re, cs, ce);
4101                         Cursor tmpcur = cur;
4102                         for (row_type r = rs; r <= re; ++r) {
4103                                 for (col_type c = cs; c <= ce; ++c) {
4104                                         // cursor follows cell:
4105                                         tmpcur.idx() = tabular.cellIndex(r, c);
4106                                         // select this cell only:
4107                                         tmpcur.pit() = 0;
4108                                         tmpcur.pos() = 0;
4109                                         tmpcur.resetAnchor();
4110                                         tmpcur.pit() = tmpcur.lastpit();
4111                                         tmpcur.pos() = tmpcur.top().lastpos();
4112                                         tmpcur.setCursor(tmpcur);
4113                                         tmpcur.setSelection();
4114                                         cell(tmpcur.idx())->dispatch(tmpcur, cmd);
4115                                 }
4116                         }
4117                         break;
4118                 } else {
4119                         cell(cur.idx())->dispatch(cur, cmd);
4120                         break;
4121                 }
4122
4123         case LFUN_INSET_SETTINGS:
4124                 // relay this lfun to Inset, not to the cell.
4125                 Inset::doDispatch(cur, cmd);
4126                 break;
4127
4128         default:
4129                 // we try to handle this event in the insets dispatch function.
4130                 cell(cur.idx())->dispatch(cur, cmd);
4131                 break;
4132         }
4133 }
4134
4135
4136 // function sets an object as defined in func_status.h:
4137 // states OK, Unknown, Disabled, On, Off.
4138 bool InsetTabular::getStatus(Cursor & cur, FuncRequest const & cmd,
4139         FuncStatus & status) const
4140 {
4141         switch (cmd.action()) {
4142         case LFUN_INSET_MODIFY: {
4143                 if (&cur.inset() != this || cmd.getArg(0) != "tabular") 
4144                         break;
4145
4146                 string const s = cmd.getArg(1);
4147                 // FIXME: We only check for the very first argument...
4148                 int action = Tabular::LAST_ACTION;
4149                 int i = 0;
4150                 for (; tabularFeature[i].action != Tabular::LAST_ACTION; ++i) {
4151                         if (tabularFeature[i].feature == s) {
4152                                 action = tabularFeature[i].action;
4153                                 break;
4154                         }
4155                 }
4156                 if (action == Tabular::LAST_ACTION) {
4157                         status.clear();
4158                         status.setUnknown(true);
4159                         return true;
4160                 }
4161
4162                 string const argument = cmd.getLongArg(2);
4163
4164                 row_type sel_row_start = 0;
4165                 row_type sel_row_end = 0;
4166                 col_type sel_col_start = 0;
4167                 col_type sel_col_end = 0;
4168                 Tabular::ltType dummyltt;
4169                 bool flag = true;
4170
4171                 getSelection(cur, sel_row_start, sel_row_end, sel_col_start, sel_col_end);
4172
4173                 switch (action) {
4174                 case Tabular::SET_PWIDTH:
4175                 case Tabular::SET_MPWIDTH:
4176                 case Tabular::SET_SPECIAL_COLUMN:
4177                 case Tabular::SET_SPECIAL_MULTICOLUMN:
4178                 case Tabular::SET_SPECIAL_MULTIROW:
4179                 case Tabular::APPEND_ROW:
4180                 case Tabular::APPEND_COLUMN:
4181                 case Tabular::DELETE_ROW:
4182                 case Tabular::DELETE_COLUMN:
4183                 case Tabular::COPY_ROW:
4184                 case Tabular::COPY_COLUMN:
4185                 case Tabular::SET_TOP_SPACE:
4186                 case Tabular::SET_BOTTOM_SPACE:
4187                 case Tabular::SET_INTERLINE_SPACE:
4188                         status.clear();
4189                         return true;
4190
4191                 case Tabular::SET_DECIMAL_POINT:
4192                         status.setEnabled(
4193                                 tabular.getAlignment(cur.idx()) == LYX_ALIGN_DECIMAL);
4194                         break;
4195
4196                 case Tabular::MULTICOLUMN:
4197                         // If a row is set as longtable caption, it must not be allowed
4198                         // to unset that this row is a multicolumn.
4199                         status.setEnabled(sel_row_start == sel_row_end
4200                                 && !tabular.ltCaption(tabular.cellRow(cur.idx())));
4201                         status.setOnOff(tabular.isMultiColumn(cur.idx()));
4202                         break;
4203
4204                 case Tabular::MULTIROW:
4205                         // If a row is set as longtable caption, it must not be allowed
4206                         // to unset that this row is a multirow.
4207                         status.setEnabled(sel_col_start == sel_col_end
4208                                 && !tabular.ltCaption(tabular.cellRow(cur.idx())));
4209                         status.setOnOff(tabular.isMultiRow(cur.idx()));
4210                         break;
4211
4212                 case Tabular::SET_ALL_LINES:
4213                 case Tabular::UNSET_ALL_LINES:
4214                 case Tabular::SET_BORDER_LINES:
4215                         status.setEnabled(!tabular.ltCaption(tabular.cellRow(cur.idx())));
4216                         break;
4217
4218                 case Tabular::SET_LINE_TOP:
4219                 case Tabular::SET_LINE_BOTTOM:
4220                 case Tabular::SET_LINE_LEFT:
4221                 case Tabular::SET_LINE_RIGHT:
4222                         status.setEnabled(!tabular.ltCaption(tabular.cellRow(cur.idx())));
4223                         break;
4224
4225                 case Tabular::TOGGLE_LINE_TOP:
4226                         status.setEnabled(!tabular.ltCaption(tabular.cellRow(cur.idx())));
4227                         status.setOnOff(tabular.topLine(cur.idx()));
4228                         break;
4229
4230                 case Tabular::TOGGLE_LINE_BOTTOM:
4231                         status.setEnabled(!tabular.ltCaption(tabular.cellRow(cur.idx())));
4232                         status.setOnOff(tabular.bottomLine(cur.idx()));
4233                         break;
4234
4235                 case Tabular::TOGGLE_LINE_LEFT:
4236                         status.setEnabled(!tabular.ltCaption(tabular.cellRow(cur.idx())));
4237                         status.setOnOff(tabular.leftLine(cur.idx()));
4238                         break;
4239
4240                 case Tabular::TOGGLE_LINE_RIGHT:
4241                         status.setEnabled(!tabular.ltCaption(tabular.cellRow(cur.idx())));
4242                         status.setOnOff(tabular.rightLine(cur.idx()));
4243                         break;
4244
4245                 case Tabular::M_ALIGN_LEFT:
4246                         flag = false;
4247                 case Tabular::ALIGN_LEFT:
4248                         status.setEnabled(!tabular.isMultiRow(cur.idx()));
4249                         status.setOnOff(tabular.getAlignment(cur.idx(), flag) == LYX_ALIGN_LEFT);
4250                         break;
4251
4252                 case Tabular::M_ALIGN_RIGHT:
4253                         flag = false;
4254                 case Tabular::ALIGN_RIGHT:
4255                         status.setEnabled(!tabular.isMultiRow(cur.idx()));
4256                         status.setOnOff(tabular.getAlignment(cur.idx(), flag) == LYX_ALIGN_RIGHT);
4257                         break;
4258
4259                 case Tabular::M_ALIGN_CENTER:
4260                         flag = false;
4261                 case Tabular::ALIGN_CENTER:
4262                         status.setEnabled(!tabular.isMultiRow(cur.idx()));
4263                         status.setOnOff(tabular.getAlignment(cur.idx(), flag) == LYX_ALIGN_CENTER);
4264                         break;
4265
4266                 case Tabular::ALIGN_BLOCK:
4267                         status.setEnabled(!tabular.getPWidth(cur.idx()).zero()
4268                                 && !tabular.isMultiRow(cur.idx()));
4269                         status.setOnOff(tabular.getAlignment(cur.idx(), flag) == LYX_ALIGN_BLOCK);
4270                         break;
4271
4272                 case Tabular::ALIGN_DECIMAL:
4273                         status.setEnabled(!tabular.isMultiRow(cur.idx()) 
4274                                 && !tabular.isMultiColumn(cur.idx()));
4275                         status.setOnOff(tabular.getAlignment(cur.idx(), true) == LYX_ALIGN_DECIMAL);
4276                         break;
4277
4278                 case Tabular::M_VALIGN_TOP:
4279                         flag = false;
4280                 case Tabular::VALIGN_TOP:
4281                         status.setEnabled(!tabular.getPWidth(cur.idx()).zero()
4282                                 && !tabular.isMultiRow(cur.idx()));
4283                         status.setOnOff(
4284                                 tabular.getVAlignment(cur.idx(), flag) == Tabular::LYX_VALIGN_TOP);
4285                         break;
4286
4287                 case Tabular::M_VALIGN_BOTTOM:
4288                         flag = false;
4289                 case Tabular::VALIGN_BOTTOM:
4290                         status.setEnabled(!tabular.getPWidth(cur.idx()).zero()
4291                                 && !tabular.isMultiRow(cur.idx()));
4292                         status.setOnOff(
4293                                 tabular.getVAlignment(cur.idx(), flag) == Tabular::LYX_VALIGN_BOTTOM);
4294                         break;
4295
4296                 case Tabular::M_VALIGN_MIDDLE:
4297                         flag = false;
4298                 case Tabular::VALIGN_MIDDLE:
4299                         status.setEnabled(!tabular.getPWidth(cur.idx()).zero()
4300                                 && !tabular.isMultiRow(cur.idx()));
4301                         status.setOnOff(
4302                                 tabular.getVAlignment(cur.idx(), flag) == Tabular::LYX_VALIGN_MIDDLE);
4303                         break;
4304
4305                 case Tabular::SET_LONGTABULAR:
4306                         status.setOnOff(tabular.is_long_tabular);
4307                         break;
4308
4309                 case Tabular::UNSET_LONGTABULAR:
4310                         status.setOnOff(!tabular.is_long_tabular);
4311                         break;
4312
4313                 case Tabular::TOGGLE_ROTATE_TABULAR:
4314                 case Tabular::SET_ROTATE_TABULAR:
4315                         status.setOnOff(tabular.rotate);
4316                         break;
4317
4318                 case Tabular::TABULAR_VALIGN_TOP:
4319                         status.setOnOff(tabular.tabular_valignment 
4320                                 == Tabular::LYX_VALIGN_TOP);
4321                         break;
4322                 case Tabular::TABULAR_VALIGN_MIDDLE:
4323                         status.setOnOff(tabular.tabular_valignment 
4324                                 == Tabular::LYX_VALIGN_MIDDLE);
4325                         break;
4326                 case Tabular::TABULAR_VALIGN_BOTTOM:
4327                         status.setOnOff(tabular.tabular_valignment 
4328                                 == Tabular::LYX_VALIGN_BOTTOM);
4329                         break;
4330
4331                 case Tabular::LONGTABULAR_ALIGN_LEFT:
4332                         status.setOnOff(tabular.longtabular_alignment 
4333                                 == Tabular::LYX_LONGTABULAR_ALIGN_LEFT);
4334                         break;
4335                 case Tabular::LONGTABULAR_ALIGN_CENTER:
4336                         status.setOnOff(tabular.longtabular_alignment 
4337                                 == Tabular::LYX_LONGTABULAR_ALIGN_CENTER);
4338                         break;
4339                 case Tabular::LONGTABULAR_ALIGN_RIGHT:
4340                         status.setOnOff(tabular.longtabular_alignment 
4341                                 == Tabular::LYX_LONGTABULAR_ALIGN_RIGHT);
4342                         break;
4343
4344                 case Tabular::UNSET_ROTATE_TABULAR:
4345                         status.setOnOff(!tabular.rotate);
4346                         break;
4347
4348                 case Tabular::TOGGLE_ROTATE_CELL:
4349                 case Tabular::SET_ROTATE_CELL:
4350                         status.setOnOff(!oneCellHasRotationState(false,
4351                                 sel_row_start, sel_row_end, sel_col_start, sel_col_end));
4352                         break;
4353
4354                 case Tabular::UNSET_ROTATE_CELL:
4355                         status.setOnOff(!oneCellHasRotationState(true,
4356                                 sel_row_start, sel_row_end, sel_col_start, sel_col_end));
4357                         break;
4358
4359                 case Tabular::SET_USEBOX:
4360                         status.setOnOff(convert<int>(argument) == tabular.getUsebox(cur.idx()));
4361                         break;
4362
4363                 // every row can only be one thing:
4364                 // either a footer or header or caption
4365                 case Tabular::SET_LTFIRSTHEAD:
4366                         status.setEnabled(sel_row_start == sel_row_end
4367                                 && !tabular.ltCaption(sel_row_start));
4368                         status.setOnOff(tabular.getRowOfLTFirstHead(sel_row_start, dummyltt));
4369                         break;
4370
4371                 case Tabular::UNSET_LTFIRSTHEAD:
4372                         status.setOnOff(!tabular.getRowOfLTFirstHead(sel_row_start, dummyltt));
4373                         break;
4374
4375                 case Tabular::SET_LTHEAD:
4376                         status.setEnabled(sel_row_start == sel_row_end
4377                                 && !tabular.ltCaption(sel_row_start));
4378                         status.setOnOff(tabular.getRowOfLTHead(sel_row_start, dummyltt));
4379                         break;
4380
4381                 case Tabular::UNSET_LTHEAD:
4382                         status.setOnOff(!tabular.getRowOfLTHead(sel_row_start, dummyltt));
4383                         break;
4384
4385                 case Tabular::SET_LTFOOT:
4386                         status.setEnabled(sel_row_start == sel_row_end
4387                                 && !tabular.ltCaption(sel_row_start));
4388                         status.setOnOff(tabular.getRowOfLTFoot(sel_row_start, dummyltt));
4389                         break;
4390
4391                 case Tabular::UNSET_LTFOOT:
4392                         status.setOnOff(!tabular.getRowOfLTFoot(sel_row_start, dummyltt));
4393                         break;
4394
4395                 case Tabular::SET_LTLASTFOOT:
4396                         status.setEnabled(sel_row_start == sel_row_end
4397                                 && !tabular.ltCaption(sel_row_start));
4398                         status.setOnOff(tabular.getRowOfLTLastFoot(sel_row_start, dummyltt));
4399                         break;
4400
4401                 case Tabular::UNSET_LTLASTFOOT:
4402                         status.setOnOff(!tabular.getRowOfLTLastFoot(sel_row_start, dummyltt));
4403                         break;
4404
4405                 case Tabular::SET_LTNEWPAGE:
4406                         status.setOnOff(tabular.getLTNewPage(sel_row_start));
4407                         break;
4408
4409                 // only one row can be the caption
4410                 // and a multirow cannot be set as caption
4411                 case Tabular::TOGGLE_LTCAPTION:
4412                         status.setEnabled(sel_row_start == sel_row_end
4413                                 && !tabular.getRowOfLTFirstHead(sel_row_start, dummyltt)
4414                                 && !tabular.getRowOfLTHead(sel_row_start, dummyltt)
4415                                 && !tabular.getRowOfLTFoot(sel_row_start, dummyltt)
4416                                 && !tabular.getRowOfLTLastFoot(sel_row_start, dummyltt)
4417                                 && (!tabular.haveLTCaption()
4418                                         || tabular.ltCaption(sel_row_start))
4419                                 && !tabular.isMultiRow(sel_row_start));
4420                         status.setOnOff(tabular.ltCaption(sel_row_start));
4421                         break;
4422
4423                 case Tabular::SET_BOOKTABS:
4424                         status.setOnOff(tabular.use_booktabs);
4425                         break;
4426
4427                 case Tabular::UNSET_BOOKTABS:
4428                         status.setOnOff(!tabular.use_booktabs);
4429                         break;
4430
4431                 default:
4432                         status.clear();
4433                         status.setEnabled(false);
4434                         break;
4435                 }
4436                 return true;
4437         }
4438
4439         // These are only enabled inside tabular
4440         case LFUN_CELL_BACKWARD:
4441         case LFUN_CELL_FORWARD:
4442                 status.setEnabled(true);
4443                 return true;
4444
4445         // disable these with multiple cells selected
4446         case LFUN_INSET_INSERT:
4447         case LFUN_TABULAR_INSERT:
4448         case LFUN_FLEX_INSERT:
4449         case LFUN_FLOAT_INSERT:
4450         case LFUN_FLOAT_WIDE_INSERT:
4451         case LFUN_FOOTNOTE_INSERT:
4452         case LFUN_MARGINALNOTE_INSERT:
4453         case LFUN_MATH_INSERT:
4454         case LFUN_MATH_MODE:
4455         case LFUN_MATH_MUTATE:
4456         case LFUN_MATH_DISPLAY:
4457         case LFUN_NOTE_INSERT:
4458         case LFUN_ARGUMENT_INSERT:
4459         case LFUN_BOX_INSERT:
4460         case LFUN_BRANCH_INSERT:
4461         case LFUN_PHANTOM_INSERT:
4462         case LFUN_WRAP_INSERT:
4463         case LFUN_PREVIEW_INSERT:
4464         case LFUN_ERT_INSERT: {
4465                 if (cur.selIsMultiCell()) {
4466                         status.setEnabled(false);
4467                         return true;
4468                 } else
4469                         return cell(cur.idx())->getStatus(cur, cmd, status);
4470         }
4471
4472         // disable in non-fixed-width cells
4473         case LFUN_NEWLINE_INSERT:
4474         case LFUN_BREAK_PARAGRAPH: {
4475                 if (tabular.getPWidth(cur.idx()).zero()) {
4476                         status.setEnabled(false);
4477                         return true;
4478                 } else
4479                         return cell(cur.idx())->getStatus(cur, cmd, status);
4480         }
4481
4482         case LFUN_NEWPAGE_INSERT:
4483                 status.setEnabled(false);
4484                 return true;
4485
4486         case LFUN_PASTE:
4487                 if (tabularStackDirty() && theClipboard().isInternal()) {
4488                         if (cur.selIsMultiCell()) {
4489                                 row_type rs, re;
4490                                 col_type cs, ce;
4491                                 getSelection(cur, rs, re, cs, ce);
4492                                 if (paste_tabular && paste_tabular->ncols() == ce - cs + 1
4493                                           && paste_tabular->nrows() == re - rs + 1)
4494                                         status.setEnabled(true);        
4495                                 else {
4496                                         status.setEnabled(false);
4497                                         status.message(_("Selection size should match clipboard content."));
4498                                 }
4499                         } else
4500                                 status.setEnabled(true);
4501                         return true;
4502                 }
4503                 return cell(cur.idx())->getStatus(cur, cmd, status);
4504
4505         case LFUN_INSET_SETTINGS:
4506                 // relay this lfun to Inset, not to the cell.
4507                 return Inset::getStatus(cur, cmd, status);
4508
4509         default:
4510                 // we try to handle this event in the insets dispatch function.
4511                 return cell(cur.idx())->getStatus(cur, cmd, status);
4512         }
4513         return false;
4514 }
4515
4516
4517 Inset::DisplayType InsetTabular::display() const
4518 {
4519                 if (tabular.is_long_tabular) {
4520                         switch (tabular.longtabular_alignment) {
4521                         case Tabular::LYX_LONGTABULAR_ALIGN_LEFT:
4522                                 return AlignLeft;
4523                         case Tabular::LYX_LONGTABULAR_ALIGN_CENTER:
4524                                 return AlignCenter;
4525                         case Tabular::LYX_LONGTABULAR_ALIGN_RIGHT:
4526                                 return AlignRight;
4527                         default:
4528                                 return AlignCenter;
4529                         }
4530                 } else
4531                         return Inline;
4532 }
4533
4534
4535 int InsetTabular::latex(odocstream & os, OutputParams const & runparams) const
4536 {
4537         return tabular.latex(os, runparams);
4538 }
4539
4540
4541 int InsetTabular::plaintext(odocstream & os, OutputParams const & runparams) const
4542 {
4543         os << '\n'; // output table on a new line
4544         int const dp = runparams.linelen > 0 ? runparams.depth : 0;
4545         tabular.plaintext(os, runparams, dp, false, 0);
4546         return PLAINTEXT_NEWLINE;
4547 }
4548
4549
4550 int InsetTabular::docbook(odocstream & os, OutputParams const & runparams) const
4551 {
4552         int ret = 0;
4553         Inset * master = 0;
4554
4555         // FIXME: Why not pass a proper DocIterator here?
4556 #if 0
4557         // if the table is inside a float it doesn't need the informaltable
4558         // wrapper. Search for it.
4559         for (master = owner(); master; master = master->owner())
4560                 if (master->lyxCode() == FLOAT_CODE)
4561                         break;
4562 #endif
4563
4564         if (!master) {
4565                 os << "<informaltable>";
4566                 ++ret;
4567         }
4568         ret += tabular.docbook(os, runparams);
4569         if (!master) {
4570                 os << "</informaltable>";
4571                 ++ret;
4572         }
4573         return ret;
4574 }
4575
4576
4577 docstring InsetTabular::xhtml(XHTMLStream & xs, OutputParams const & rp) const
4578 {
4579         // FIXME XHTML
4580         // It'd be better to be able to get this from an InsetLayout, but at present
4581         // InsetLayouts do not seem really to work for things that aren't InsetTexts.
4582         xs << html::StartTag("table");
4583         docstring ret = tabular.xhtml(xs, rp);
4584         xs << html::EndTag("table");
4585         return ret;
4586 }
4587
4588
4589 void InsetTabular::validate(LaTeXFeatures & features) const
4590 {
4591         tabular.validate(features);
4592         // FIXME XHTML
4593         // It'd be better to be able to get this from an InsetLayout, but at present
4594         // InsetLayouts do not seem really to work for things that aren't InsetTexts.
4595         if (features.runparams().flavor == OutputParams::HTML)
4596                 features.addPreambleSnippet("<style type=\"text/css\">\n"
4597       "table { border: 1px solid black; display: inline-block; }\n"
4598       "td { border: 1px solid black; padding: 0.5ex; }\n"
4599       "</style>");
4600 }
4601
4602
4603 shared_ptr<InsetTableCell const> InsetTabular::cell(idx_type idx) const
4604 {
4605         return tabular.cellInset(idx);
4606 }
4607
4608
4609 shared_ptr<InsetTableCell> InsetTabular::cell(idx_type idx)
4610 {
4611         return tabular.cellInset(idx);
4612 }
4613
4614
4615 void InsetTabular::cursorPos(BufferView const & bv,
4616                 CursorSlice const & sl, bool boundary, int & x, int & y) const
4617 {
4618         cell(sl.idx())->cursorPos(bv, sl, boundary, x, y);
4619
4620         int const row = tabular.cellRow(sl.idx());
4621         int const col = tabular.cellColumn(sl.idx());
4622
4623         // y offset     correction
4624         for (int r = 0; r < row; ++r)
4625                 y += tabular.rowDescent(r) + tabular.rowAscent(r + 1) 
4626                         + tabular.interRowSpace(r + 1);
4627
4628         y += tabular.textVOffset(sl.idx());
4629
4630         // x offset correction
4631         for (int c = 0; c < col; ++c)
4632                 x += tabular.column_info[c].width;
4633         
4634         x += tabular.textHOffset(sl.idx());
4635         x += ADD_TO_TABULAR_WIDTH;
4636         x += scx_;
4637 }
4638
4639
4640 int InsetTabular::dist(BufferView & bv, idx_type const cell, int x, int y) const
4641 {
4642         int xx = 0;
4643         int yy = 0;
4644         Inset const & inset = *tabular.cellInset(cell);
4645         Point o = bv.coordCache().getInsets().xy(&inset);
4646         int const xbeg = o.x_ - tabular.textHOffset(cell);
4647         int const xend = xbeg + tabular.columnWidth(cell);
4648         row_type const row = tabular.cellRow(cell);
4649         int const ybeg = o.y_ - tabular.rowAscent(row)
4650                 - tabular.interRowSpace(row);
4651         int const yend = ybeg + tabular.cellHeight(cell);
4652
4653         if (x < xbeg)
4654                 xx = xbeg - x;
4655         else if (x > xend)
4656                 xx = x - xend;
4657
4658         if (y < ybeg)
4659                 yy = ybeg - y;
4660         else if (y > yend)
4661                 yy = y - yend;
4662
4663         //lyxerr << " xbeg=" << xbeg << "  xend=" << xend
4664         //       << " ybeg=" << ybeg << " yend=" << yend
4665         //       << " xx=" << xx << " yy=" << yy
4666         //       << " dist=" << xx + yy << endl;
4667         return xx + yy;
4668 }
4669
4670
4671 Inset * InsetTabular::editXY(Cursor & cur, int x, int y)
4672 {
4673         //lyxerr << "InsetTabular::editXY: " << this << endl;
4674         cur.setSelection(false);
4675         cur.push(*this);
4676         cur.idx() = getNearestCell(cur.bv(), x, y);
4677         resetPos(cur);
4678         return cur.bv().textMetrics(&cell(cur.idx())->text()).editXY(cur, x, y);
4679 }
4680
4681
4682 void InsetTabular::setCursorFromCoordinates(Cursor & cur, int x, int y) const
4683 {
4684         cur.idx() = getNearestCell(cur.bv(), x, y);
4685         cur.bv().textMetrics(&cell(cur.idx())->text()).setCursorFromCoordinates(cur, x, y);
4686 }
4687
4688
4689 InsetTabular::idx_type InsetTabular::getNearestCell(BufferView & bv, int x, int y) const
4690 {
4691         idx_type idx_min = 0;
4692         int dist_min = numeric_limits<int>::max();
4693         for (idx_type i = 0, n = nargs(); i != n; ++i) {
4694                 if (bv.coordCache().getInsets().has(tabular.cellInset(i).get())) {
4695                         int const d = dist(bv, i, x, y);
4696                         if (d < dist_min) {
4697                                 dist_min = d;
4698                                 idx_min = i;
4699                         }
4700                 }
4701         }
4702         return idx_min;
4703 }
4704
4705
4706 int InsetTabular::cellXPos(idx_type const cell) const
4707 {
4708         col_type col = tabular.cellColumn(cell);
4709         int lx = 0;
4710         for (col_type c = 0; c < col; ++c)
4711                 lx += tabular.columnWidth(c);
4712
4713         return lx;
4714 }
4715
4716
4717 void InsetTabular::resetPos(Cursor & cur) const
4718 {
4719         BufferView & bv = cur.bv();
4720         int const maxwidth = bv.workWidth();
4721
4722         int const scx_old = scx_;
4723         int const i = cur.find(this);
4724         if (i == -1) {
4725                 scx_ = 0;
4726         } else {
4727                 int const X1 = 0;
4728                 int const X2 = maxwidth;
4729                 int const offset = ADD_TO_TABULAR_WIDTH + 2;
4730                 int const x1 = xo(cur.bv()) + cellXPos(cur[i].idx()) + offset;
4731                 int const x2 = x1 + tabular.columnWidth(cur[i].idx());
4732
4733                 if (x1 < X1)
4734                         scx_ = X1 + 20 - x1;
4735                 else if (x2 > X2)
4736                         scx_ = X2 - 20 - x2;
4737                 else
4738                         scx_ = 0;
4739         }
4740
4741         // only update if offset changed
4742         if (scx_ != scx_old)
4743                 cur.updateFlags(Update::Force | Update::FitCursor);
4744 }
4745
4746
4747 void InsetTabular::moveNextCell(Cursor & cur, EntryDirection entry_from)
4748 {
4749         row_type const row = tabular.cellRow(cur.idx());
4750         col_type const col = tabular.cellColumn(cur.idx());
4751
4752         if (isRightToLeft(cur)) {
4753                 if (tabular.cellColumn(cur.idx()) == 0) {
4754                         if (row == tabular.nrows() - 1)
4755                                 return;
4756                         cur.idx() = tabular.cellBelow(tabular.getLastCellInRow(row));
4757                 } else {
4758                         if (cur.idx() == 0)
4759                                 return;
4760                         if (col == 0)
4761                                 cur.idx() = tabular.getLastCellInRow(row - 1);
4762                         else
4763                                 cur.idx() = tabular.cellIndex(row, col - 1);
4764                 }
4765         } else {
4766                 if (tabular.isLastCell(cur.idx()))
4767                         return;
4768                 if (cur.idx() == tabular.getLastCellInRow(row))
4769                         cur.idx() = tabular.cellIndex(row + 1, 0);
4770                 else {
4771                         col_type const colnextcell = col + tabular.columnSpan(cur.idx());
4772                         cur.idx() = tabular.cellIndex(row, colnextcell);
4773                 }
4774         }
4775
4776         cur.boundary(false);
4777
4778         if (cur.selIsMultiCell()) {
4779                 cur.pit() = cur.lastpit();
4780                 cur.pos() = cur.lastpos();
4781                 resetPos(cur);
4782                 return;
4783         }
4784
4785         cur.pit() = 0;
4786         cur.pos() = 0;
4787
4788         // in visual mode, place cursor at extreme left or right
4789         
4790         switch(entry_from) {
4791
4792         case ENTRY_DIRECTION_RIGHT:
4793                 cur.posVisToRowExtremity(false /* !left */);
4794                 break;
4795         case ENTRY_DIRECTION_LEFT:
4796                 cur.posVisToRowExtremity(true /* left */);
4797                 break;
4798         case ENTRY_DIRECTION_IGNORE:
4799                 // nothing to do in this case
4800                 break;
4801
4802         }
4803         cur.setCurrentFont();
4804         resetPos(cur);
4805 }
4806
4807
4808 void InsetTabular::movePrevCell(Cursor & cur, EntryDirection entry_from)
4809 {
4810         row_type const row = tabular.cellRow(cur.idx());
4811         col_type const col = tabular.cellColumn(cur.idx());
4812
4813         if (isRightToLeft(cur)) {
4814                 if (cur.idx() == tabular.getLastCellInRow(row)) {
4815                         if (row == 0)
4816                                 return;
4817                         cur.idx() = tabular.getFirstCellInRow(row);
4818                         cur.idx() = tabular.cellAbove(cur.idx());
4819                 } else {
4820                         if (tabular.isLastCell(cur.idx()))
4821                                 return;
4822                         if (cur.idx() == tabular.getLastCellInRow(row))
4823                                 cur.idx() = tabular.cellIndex(row + 1, 0);
4824                         else
4825                                 cur.idx() = tabular.cellIndex(row, col + 1);
4826                 }
4827         } else {
4828                 if (cur.idx() == 0) // first cell
4829                         return;
4830                 if (col == 0)
4831                         cur.idx() = tabular.getLastCellInRow(row - 1);
4832                 else
4833                         cur.idx() = tabular.cellIndex(row, col - 1);
4834         }
4835
4836         if (cur.selIsMultiCell()) {
4837                 cur.pit() = cur.lastpit();
4838                 cur.pos() = cur.lastpos();
4839                 resetPos(cur);
4840                 return;
4841         }
4842
4843         cur.pit() = cur.lastpit();
4844         cur.pos() = cur.lastpos();
4845
4846         // in visual mode, place cursor at extreme left or right
4847         
4848         switch(entry_from) {
4849
4850         case ENTRY_DIRECTION_RIGHT:
4851                 cur.posVisToRowExtremity(false /* !left */);
4852                 break;
4853         case ENTRY_DIRECTION_LEFT:
4854                 cur.posVisToRowExtremity(true /* left */);
4855                 break;
4856         case ENTRY_DIRECTION_IGNORE:
4857                 // nothing to do in this case
4858                 break;
4859
4860         }
4861         cur.setCurrentFont();
4862         resetPos(cur);
4863 }
4864
4865
4866 bool InsetTabular::tabularFeatures(Cursor & cur, string const & argument)
4867 {
4868         istringstream is(argument);
4869         string s;
4870         is >> s;
4871         if (insetCode(s) != TABULAR_CODE)
4872                 return false;
4873
4874         // Safe guard.
4875         size_t safe_guard = 0;
4876         for (;;) {
4877                 if (is.eof())
4878                         break;
4879                 safe_guard++;
4880                 if (safe_guard > 1000) {
4881                         LYXERR0("parameter max count reached!");
4882                         break;
4883                 }
4884                 is >> s;
4885                 Tabular::Feature action = Tabular::LAST_ACTION;
4886
4887                 size_t i = 0;
4888                 for (; tabularFeature[i].action != Tabular::LAST_ACTION; ++i) {
4889                         if (s != tabularFeature[i].feature)
4890                                 continue;
4891
4892                         action = tabularFeature[i].action;
4893                         break;
4894                 }
4895                 if (action == Tabular::LAST_ACTION) {
4896                         LYXERR0("Feature not found " << s);
4897                         continue;
4898                 }
4899                 string val;
4900                 if (tabularFeature[i].need_value)
4901                         is >> val;
4902                 LYXERR(Debug::DEBUG, "Feature: " << s << "\t\tvalue: " << val);
4903                 tabularFeatures(cur, action, val);
4904         }
4905         return true;
4906 }
4907
4908
4909 static void checkLongtableSpecial(Tabular::ltType & ltt,
4910                           string const & special, bool & flag)
4911 {
4912         if (special == "dl_above") {
4913                 ltt.topDL = flag;
4914                 ltt.set = false;
4915         } else if (special == "dl_below") {
4916                 ltt.bottomDL = flag;
4917                 ltt.set = false;
4918         } else if (special == "empty") {
4919                 ltt.empty = flag;
4920                 ltt.set = false;
4921         } else if (flag) {
4922                 ltt.empty = false;
4923                 ltt.set = true;
4924         }
4925 }
4926
4927
4928 bool InsetTabular::oneCellHasRotationState(bool rotated,
4929                 row_type row_start, row_type row_end,
4930                 col_type col_start, col_type col_end) const 
4931 {
4932         for (row_type r = row_start; r <= row_end; ++r)
4933                 for (col_type c = col_start; c <= col_end; ++c)
4934                         if (tabular.getRotateCell(tabular.cellIndex(r, c)) == rotated)
4935                                 return true;
4936
4937         return false;
4938 }
4939
4940 void InsetTabular::tabularFeatures(Cursor & cur,
4941         Tabular::Feature feature, string const & value)
4942 {
4943         col_type sel_col_start;
4944         col_type sel_col_end;
4945         row_type sel_row_start;
4946         row_type sel_row_end;
4947         bool setLines = false;
4948         LyXAlignment setAlign = LYX_ALIGN_LEFT;
4949         Tabular::VAlignment setVAlign = Tabular::LYX_VALIGN_TOP;
4950
4951         switch (feature) {
4952
4953         case Tabular::M_ALIGN_LEFT:
4954         case Tabular::ALIGN_LEFT:
4955                 setAlign = LYX_ALIGN_LEFT;
4956                 break;
4957
4958         case Tabular::M_ALIGN_RIGHT:
4959         case Tabular::ALIGN_RIGHT:
4960                 setAlign = LYX_ALIGN_RIGHT;
4961                 break;
4962
4963         case Tabular::M_ALIGN_CENTER:
4964         case Tabular::ALIGN_CENTER:
4965                 setAlign = LYX_ALIGN_CENTER;
4966                 break;
4967
4968         case Tabular::ALIGN_BLOCK:
4969                 setAlign = LYX_ALIGN_BLOCK;
4970                 break;
4971
4972         case Tabular::ALIGN_DECIMAL:
4973                 setAlign = LYX_ALIGN_DECIMAL;
4974                 break;
4975
4976         case Tabular::M_VALIGN_TOP:
4977         case Tabular::VALIGN_TOP:
4978                 setVAlign = Tabular::LYX_VALIGN_TOP;
4979                 break;
4980
4981         case Tabular::M_VALIGN_BOTTOM:
4982         case Tabular::VALIGN_BOTTOM:
4983                 setVAlign = Tabular::LYX_VALIGN_BOTTOM;
4984                 break;
4985
4986         case Tabular::M_VALIGN_MIDDLE:
4987         case Tabular::VALIGN_MIDDLE:
4988                 setVAlign = Tabular::LYX_VALIGN_MIDDLE;
4989                 break;
4990
4991         default:
4992                 break;
4993         }
4994
4995         cur.recordUndoInset(ATOMIC_UNDO);
4996
4997         getSelection(cur, sel_row_start, sel_row_end, sel_col_start, sel_col_end);
4998         row_type const row = tabular.cellRow(cur.idx());
4999         col_type const column = tabular.cellColumn(cur.idx());
5000         bool flag = true;
5001         Tabular::ltType ltt;
5002
5003         switch (feature) {
5004
5005         case Tabular::SET_PWIDTH: {
5006                 Length const len(value);
5007                 tabular.setColumnPWidth(cur, cur.idx(), len);
5008                 if (len.zero()
5009                     && tabular.getAlignment(cur.idx(), true) == LYX_ALIGN_BLOCK)
5010                         tabularFeatures(cur, Tabular::ALIGN_CENTER, string());
5011                 break;
5012         }
5013
5014         case Tabular::SET_MPWIDTH:
5015                 tabular.setMColumnPWidth(cur, cur.idx(), Length(value));
5016                 break;
5017
5018         case Tabular::SET_SPECIAL_COLUMN:
5019         case Tabular::SET_SPECIAL_MULTICOLUMN:
5020                 if (value == "none")
5021                         tabular.setAlignSpecial(cur.idx(), docstring(), feature);
5022                 else
5023                         tabular.setAlignSpecial(cur.idx(), from_utf8(value), feature);
5024                 break;
5025
5026         case Tabular::SET_SPECIAL_MULTIROW:
5027                 // nothing to do
5028                 break;
5029
5030         case Tabular::APPEND_ROW:
5031                 // append the row into the tabular
5032                 tabular.appendRow(cur.idx());
5033                 break;
5034
5035         case Tabular::APPEND_COLUMN:
5036                 // append the column into the tabular
5037                 tabular.appendColumn(cur.idx());
5038                 cur.idx() = tabular.cellIndex(row, column);
5039                 break;
5040
5041         case Tabular::DELETE_ROW:
5042                 for (row_type r = sel_row_start; r <= sel_row_end; ++r)
5043                         tabular.deleteRow(sel_row_start);
5044                 if (sel_row_start >= tabular.nrows())
5045                         --sel_row_start;
5046                 cur.idx() = tabular.cellIndex(sel_row_start, column);
5047                 cur.pit() = 0;
5048                 cur.pos() = 0;
5049                 cur.setSelection(false);
5050                 break;
5051
5052         case Tabular::DELETE_COLUMN:
5053                 for (col_type c = sel_col_start; c <= sel_col_end; ++c)
5054                         tabular.deleteColumn(sel_col_start);
5055                 if (sel_col_start >= tabular.ncols())
5056                         --sel_col_start;
5057                 cur.idx() = tabular.cellIndex(row, sel_col_start);
5058                 cur.pit() = 0;
5059                 cur.pos() = 0;
5060                 cur.setSelection(false);
5061                 break;
5062
5063         case Tabular::COPY_ROW:
5064                 tabular.copyRow(row);
5065                 break;
5066
5067         case Tabular::COPY_COLUMN:
5068                 tabular.copyColumn(column);
5069                 cur.idx() = tabular.cellIndex(row, column);
5070                 break;
5071
5072         case Tabular::SET_LINE_TOP:
5073         case Tabular::TOGGLE_LINE_TOP: {
5074                 bool lineSet = (feature == Tabular::SET_LINE_TOP)
5075                                ? (value == "true") : !tabular.topLine(cur.idx());
5076                 for (row_type r = sel_row_start; r <= sel_row_end; ++r)
5077                         for (col_type c = sel_col_start; c <= sel_col_end; ++c)
5078                                 tabular.setTopLine(tabular.cellIndex(r, c), lineSet);
5079                 break;
5080         }
5081
5082         case Tabular::SET_LINE_BOTTOM:
5083         case Tabular::TOGGLE_LINE_BOTTOM: {
5084                 bool lineSet = (feature == Tabular::SET_LINE_BOTTOM)
5085                                ? (value == "true") : !tabular.bottomLine(cur.idx());
5086                 for (row_type r = sel_row_start; r <= sel_row_end; ++r)
5087                         for (col_type c = sel_col_start; c <= sel_col_end; ++c)
5088                                 tabular.setBottomLine(tabular.cellIndex(r, c), lineSet);
5089                 break;
5090         }
5091
5092         case Tabular::SET_LINE_LEFT:
5093         case Tabular::TOGGLE_LINE_LEFT: {
5094                 bool lineSet = (feature == Tabular::SET_LINE_LEFT)
5095                                ? (value == "true") : !tabular.leftLine(cur.idx());
5096                 for (row_type r = sel_row_start; r <= sel_row_end; ++r)
5097                         for (col_type c = sel_col_start; c <= sel_col_end; ++c)
5098                                 tabular.setLeftLine(tabular.cellIndex(r, c), lineSet);
5099                 break;
5100         }
5101
5102         case Tabular::SET_LINE_RIGHT:
5103         case Tabular::TOGGLE_LINE_RIGHT: {
5104                 bool lineSet = (feature == Tabular::SET_LINE_RIGHT)
5105                                ? (value == "true") : !tabular.rightLine(cur.idx());
5106                 for (row_type r = sel_row_start; r <= sel_row_end; ++r)
5107                         for (col_type c = sel_col_start; c <= sel_col_end; ++c)
5108                                 tabular.setRightLine(tabular.cellIndex(r, c), lineSet);
5109                 break;
5110         }
5111
5112         case Tabular::M_ALIGN_LEFT:
5113         case Tabular::M_ALIGN_RIGHT:
5114         case Tabular::M_ALIGN_CENTER:
5115                 flag = false;
5116         case Tabular::ALIGN_LEFT:
5117         case Tabular::ALIGN_RIGHT:
5118         case Tabular::ALIGN_CENTER:
5119         case Tabular::ALIGN_BLOCK:
5120         case Tabular::ALIGN_DECIMAL:
5121                 for (row_type r = sel_row_start; r <= sel_row_end; ++r)
5122                         for (col_type c = sel_col_start; c <= sel_col_end; ++c)
5123                                 tabular.setAlignment(tabular.cellIndex(r, c), setAlign, flag);
5124                 break;
5125
5126         case Tabular::M_VALIGN_TOP:
5127         case Tabular::M_VALIGN_BOTTOM:
5128         case Tabular::M_VALIGN_MIDDLE:
5129                 flag = false;
5130         case Tabular::VALIGN_TOP:
5131         case Tabular::VALIGN_BOTTOM:
5132         case Tabular::VALIGN_MIDDLE:
5133                 for (row_type r = sel_row_start; r <= sel_row_end; ++r)
5134                         for (col_type c = sel_col_start; c <= sel_col_end; ++c)
5135                                 tabular.setVAlignment(tabular.cellIndex(r, c), setVAlign, flag);
5136                 break;
5137
5138         case Tabular::MULTICOLUMN: {
5139                 if (!cur.selection()) {
5140                         // just multicol for one single cell
5141                         // check whether we are completely in a multicol
5142                         if (tabular.isMultiColumn(cur.idx()))
5143                                 tabular.unsetMultiColumn(cur.idx());
5144                         else
5145                                 tabular.setMultiColumn(cur.idx(), 1);
5146                         break;
5147                 }
5148                 // we have a selection so this means we just add all this
5149                 // cells to form a multicolumn cell
5150                 idx_type const s_start = cur.selBegin().idx();
5151                 row_type const col_start = tabular.cellColumn(s_start);
5152                 row_type const col_end = tabular.cellColumn(cur.selEnd().idx());
5153                 cur.idx() = tabular.setMultiColumn(s_start, col_end - col_start + 1);
5154                 cur.pit() = 0;
5155                 cur.pos() = 0;
5156                 cur.setSelection(false);
5157                 break;
5158         }
5159         
5160         case Tabular::MULTIROW: {
5161                 if (!cur.selection()) {
5162                         // just multirow for one single cell
5163                         // check whether we are completely in a multirow
5164                         if (tabular.isMultiRow(cur.idx()))
5165                                 tabular.unsetMultiRow(cur.idx());
5166                         else
5167                                 tabular.setMultiRow(cur.idx(), 1);
5168                         break;
5169                 }
5170                 // we have a selection so this means we just add all this
5171                 // cells to form a multirow cell
5172                 idx_type const s_start = cur.selBegin().idx();
5173                 row_type const row_start = tabular.cellRow(s_start);
5174                 row_type const row_end = tabular.cellRow(cur.selEnd().idx());
5175                 cur.idx() = tabular.setMultiRow(s_start, row_end - row_start + 1);
5176                 cur.pit() = 0;
5177                 cur.pos() = 0;
5178                 cur.setSelection(false);
5179                 break;
5180         }
5181
5182         case Tabular::SET_ALL_LINES:
5183                 setLines = true;
5184         case Tabular::UNSET_ALL_LINES:
5185                 for (row_type r = sel_row_start; r <= sel_row_end; ++r)
5186                         for (col_type c = sel_col_start; c <= sel_col_end; ++c) {
5187                                 idx_type const cell = tabular.cellIndex(r, c);
5188                                 tabular.setTopLine(cell, setLines);
5189                                 tabular.setBottomLine(cell, setLines);
5190                                 tabular.setRightLine(cell, setLines);
5191                                 tabular.setLeftLine(cell, setLines);
5192                         }
5193                 break;
5194
5195         case Tabular::SET_BORDER_LINES:
5196                 for (row_type r = sel_row_start; r <= sel_row_end; ++r) {
5197                         tabular.setLeftLine(tabular.cellIndex(r, sel_col_start), true);
5198                         tabular.setRightLine(tabular.cellIndex(r, sel_col_end), true);
5199                 }
5200                 for (col_type c = sel_col_start; c <= sel_col_end; ++c) {
5201                         tabular.setTopLine(tabular.cellIndex(sel_row_start, c), true);
5202                         tabular.setBottomLine(tabular.cellIndex(sel_row_end, c), true);
5203                 }
5204                 break;
5205
5206         case Tabular::SET_LONGTABULAR:
5207                 tabular.is_long_tabular = true;
5208                 break;
5209
5210         case Tabular::UNSET_LONGTABULAR:
5211                 for (row_type r = 0; r < tabular.nrows(); ++r) {
5212                         if (tabular.ltCaption(r)) {
5213                                 cur.idx() = tabular.cellIndex(r, 0);
5214                                 cur.pit() = 0;
5215                                 cur.pos() = 0;
5216                                 tabularFeatures(cur, Tabular::TOGGLE_LTCAPTION);
5217                         }
5218                 }
5219                 tabular.is_long_tabular = false;
5220                 break;
5221
5222         case Tabular::SET_ROTATE_TABULAR:
5223                 tabular.rotate = true;
5224                 break;
5225
5226         case Tabular::UNSET_ROTATE_TABULAR:
5227                 tabular.rotate = false;
5228                 break;
5229
5230         case Tabular::TOGGLE_ROTATE_TABULAR:
5231                 tabular.rotate = !tabular.rotate;
5232                 break;
5233
5234         case Tabular::TABULAR_VALIGN_TOP:
5235                 tabular.tabular_valignment = Tabular::LYX_VALIGN_TOP;
5236                 break;
5237
5238         case Tabular::TABULAR_VALIGN_MIDDLE:
5239                 tabular.tabular_valignment = Tabular::LYX_VALIGN_MIDDLE;
5240                 break;
5241
5242         case Tabular::TABULAR_VALIGN_BOTTOM:
5243                 tabular.tabular_valignment = Tabular::LYX_VALIGN_BOTTOM;
5244                 break;
5245
5246         case Tabular::LONGTABULAR_ALIGN_LEFT:
5247                 tabular.longtabular_alignment = Tabular::LYX_LONGTABULAR_ALIGN_LEFT;
5248                 break;
5249
5250         case Tabular::LONGTABULAR_ALIGN_CENTER:
5251                 tabular.longtabular_alignment = Tabular::LYX_LONGTABULAR_ALIGN_CENTER;
5252                 break;
5253
5254         case Tabular::LONGTABULAR_ALIGN_RIGHT:
5255                 tabular.longtabular_alignment = Tabular::LYX_LONGTABULAR_ALIGN_RIGHT;
5256                 break;
5257
5258                 
5259
5260         case Tabular::SET_ROTATE_CELL:
5261                 for (row_type r = sel_row_start; r <= sel_row_end; ++r)
5262                         for (col_type c = sel_col_start; c <= sel_col_end; ++c)
5263                                 tabular.setRotateCell(tabular.cellIndex(r, c), true);
5264                 break;
5265
5266         case Tabular::UNSET_ROTATE_CELL:
5267                 for (row_type r = sel_row_start; r <= sel_row_end; ++r)
5268                         for (col_type c = sel_col_start; c <= sel_col_end; ++c)
5269                                 tabular.setRotateCell(tabular.cellIndex(r, c), false);
5270                 break;
5271
5272         case Tabular::TOGGLE_ROTATE_CELL:
5273                 {
5274                 bool oneNotRotated = oneCellHasRotationState(false,
5275                         sel_row_start, sel_row_end, sel_col_start, sel_col_end);
5276
5277                 for (row_type r = sel_row_start; r <= sel_row_end; ++r)
5278                         for (col_type c = sel_col_start; c <= sel_col_end; ++c)
5279                                 tabular.setRotateCell(tabular.cellIndex(r, c),
5280                                                                           oneNotRotated);
5281                 }
5282                 break;
5283
5284         case Tabular::SET_USEBOX: {
5285                 Tabular::BoxType val = Tabular::BoxType(convert<int>(value));
5286                 if (val == tabular.getUsebox(cur.idx()))
5287                         val = Tabular::BOX_NONE;
5288                 for (row_type r = sel_row_start; r <= sel_row_end; ++r)
5289                         for (col_type c = sel_col_start; c <= sel_col_end; ++c)
5290                                 tabular.setUsebox(tabular.cellIndex(r, c), val);
5291                 break;
5292         }
5293
5294         case Tabular::UNSET_LTFIRSTHEAD:
5295                 flag = false;
5296         case Tabular::SET_LTFIRSTHEAD:
5297                 tabular.getRowOfLTFirstHead(row, ltt);
5298                 checkLongtableSpecial(ltt, value, flag);
5299                 tabular.setLTHead(row, flag, ltt, true);
5300                 break;
5301
5302         case Tabular::UNSET_LTHEAD:
5303                 flag = false;
5304         case Tabular::SET_LTHEAD:
5305                 tabular.getRowOfLTHead(row, ltt);
5306                 checkLongtableSpecial(ltt, value, flag);
5307                 tabular.setLTHead(row, flag, ltt, false);
5308                 break;
5309
5310         case Tabular::UNSET_LTFOOT:
5311                 flag = false;
5312         case Tabular::SET_LTFOOT:
5313                 tabular.getRowOfLTFoot(row, ltt);
5314                 checkLongtableSpecial(ltt, value, flag);
5315                 tabular.setLTFoot(row, flag, ltt, false);
5316                 break;
5317
5318         case Tabular::UNSET_LTLASTFOOT:
5319                 flag = false;
5320         case Tabular::SET_LTLASTFOOT:
5321                 tabular.getRowOfLTLastFoot(row, ltt);
5322                 checkLongtableSpecial(ltt, value, flag);
5323                 tabular.setLTFoot(row, flag, ltt, true);
5324                 break;
5325
5326         case Tabular::SET_LTNEWPAGE:
5327                 tabular.setLTNewPage(row, !tabular.getLTNewPage(row));
5328                 break;
5329
5330         case Tabular::TOGGLE_LTCAPTION: {
5331                 bool const set = !tabular.ltCaption(row);
5332                 cur.idx() = tabular.setLTCaption(row, set);
5333                 cur.pit() = 0;
5334                 cur.pos() = 0;
5335                 cur.setSelection(false);
5336
5337                 if (set) {
5338                         // When a row is set as caption, then also insert
5339                         // a caption. Otherwise the LaTeX output is broken.
5340                         lyx::dispatch(FuncRequest(LFUN_INSET_SELECT_ALL));
5341                         lyx::dispatch(FuncRequest(LFUN_CAPTION_INSERT));
5342                 } else {
5343                         FuncRequest fr(LFUN_INSET_DISSOLVE, "caption");
5344                         if (lyx::getStatus(fr).enabled())
5345                                 lyx::dispatch(fr);
5346                 }
5347                 break;
5348         }
5349
5350         case Tabular::SET_BOOKTABS:
5351                 tabular.use_booktabs = true;
5352                 break;
5353
5354         case Tabular::UNSET_BOOKTABS:
5355                 tabular.use_booktabs = false;
5356                 break;
5357
5358         case Tabular::SET_TOP_SPACE: {
5359                 Length len;
5360                 if (value == "default")
5361                         for (row_type r = sel_row_start; r <= sel_row_end; ++r)
5362                                 tabular.row_info[r].top_space_default = true;
5363                 else if (value == "none")
5364                         for (row_type r = sel_row_start; r <= sel_row_end; ++r) {
5365                                 tabular.row_info[r].top_space_default = false;
5366                                 tabular.row_info[r].top_space = len;
5367                         }
5368                 else if (isValidLength(value, &len))
5369                         for (row_type r = sel_row_start; r <= sel_row_end; ++r) {
5370                                 tabular.row_info[r].top_space_default = false;
5371                                 tabular.row_info[r].top_space = len;
5372                         }
5373                 break;
5374         }
5375
5376         case Tabular::SET_BOTTOM_SPACE: {
5377                 Length len;
5378                 if (value == "default")
5379                         for (row_type r = sel_row_start; r <= sel_row_end; ++r)
5380                                 tabular.row_info[r].bottom_space_default = true;
5381                 else if (value == "none")
5382                         for (row_type r = sel_row_start; r <= sel_row_end; ++r) {
5383                                 tabular.row_info[r].bottom_space_default = false;
5384                                 tabular.row_info[r].bottom_space = len;
5385                         }
5386                 else if (isValidLength(value, &len))
5387                         for (row_type r = sel_row_start; r <= sel_row_end; ++r) {
5388                                 tabular.row_info[r].bottom_space_default = false;
5389                                 tabular.row_info[r].bottom_space = len;
5390                         }
5391                 break;
5392         }
5393
5394         case Tabular::SET_INTERLINE_SPACE: {
5395                 Length len;
5396                 if (value == "default")
5397                         for (row_type r = sel_row_start; r <= sel_row_end; ++r)
5398                                 tabular.row_info[r].interline_space_default = true;
5399                 else if (value == "none")
5400                         for (row_type r = sel_row_start; r <= sel_row_end; ++r) {
5401                                 tabular.row_info[r].interline_space_default = false;
5402                                 tabular.row_info[r].interline_space = len;
5403                         }
5404                 else if (isValidLength(value, &len))
5405                         for (row_type r = sel_row_start; r <= sel_row_end; ++r) {
5406                                 tabular.row_info[r].interline_space_default = false;
5407                                 tabular.row_info[r].interline_space = len;
5408                         }
5409                 break;
5410         }
5411
5412         case Tabular::SET_DECIMAL_POINT:
5413                 for (col_type c = sel_col_start; c <= sel_col_end; ++c)
5414                         tabular.column_info[c].decimal_point = from_utf8(value);
5415                 break;
5416
5417         // dummy stuff just to avoid warnings
5418         case Tabular::LAST_ACTION:
5419                 break;
5420         }
5421 }
5422
5423
5424 bool InsetTabular::copySelection(Cursor & cur)
5425 {
5426         if (!cur.selection())
5427                 return false;
5428
5429         row_type rs, re;
5430         col_type cs, ce;
5431         getSelection(cur, rs, re, cs, ce);
5432
5433         paste_tabular.reset(new Tabular(tabular));
5434
5435         for (row_type r = 0; r < rs; ++r)
5436                 paste_tabular->deleteRow(0);
5437
5438         row_type const rows = re - rs + 1;
5439         while (paste_tabular->nrows() > rows)
5440                 paste_tabular->deleteRow(rows);
5441
5442         for (col_type c = 0; c < cs; ++c)
5443                 paste_tabular->deleteColumn(0);
5444
5445         col_type const columns = ce - cs + 1;
5446         while (paste_tabular->ncols() > columns)
5447                 paste_tabular->deleteColumn(columns);
5448
5449         paste_tabular->setBuffer(tabular.buffer());
5450
5451         odocstringstream os;
5452         OutputParams const runparams(0);
5453         paste_tabular->plaintext(os, runparams, 0, true, '\t');
5454         // Needed for the "Edit->Paste recent" menu and the system clipboard.
5455         cap::copySelection(cur, os.str());
5456
5457         // mark tabular stack dirty
5458         // FIXME: this is a workaround for bug 1919. Should be removed for 1.5,
5459         // when we (hopefully) have a one-for-all paste mechanism.
5460         // This must be called after cap::copySelection.
5461         dirtyTabularStack(true);
5462
5463         return true;
5464 }
5465
5466
5467 bool InsetTabular::pasteClipboard(Cursor & cur)
5468 {
5469         if (!paste_tabular)
5470                 return false;
5471         col_type actcol = tabular.cellColumn(cur.idx());
5472         row_type actrow = tabular.cellRow(cur.idx());
5473
5474         if (cur.selIsMultiCell()) {
5475                 row_type re;
5476                 col_type ce;
5477                 getSelection(cur, actrow, re, actcol, ce);
5478         }
5479
5480         for (row_type r1 = 0, r2 = actrow;
5481              r1 < paste_tabular->nrows() && r2 < tabular.nrows();
5482              ++r1, ++r2) {
5483                 for (col_type c1 = 0, c2 = actcol;
5484                     c1 < paste_tabular->ncols() && c2 < tabular.ncols();
5485                     ++c1, ++c2) {
5486                         if (paste_tabular->isPartOfMultiColumn(r1, c1) &&
5487                               tabular.isPartOfMultiColumn(r2, c2))
5488                                 continue;
5489                         if (paste_tabular->isPartOfMultiColumn(r1, c1)) {
5490                                 --c2;
5491                                 continue;
5492                         }
5493                         if (tabular.isPartOfMultiColumn(r2, c2)) {
5494                                 --c1;
5495                                 continue;
5496                         }
5497                         shared_ptr<InsetTableCell> inset(
5498                                 new InsetTableCell(*paste_tabular->cellInset(r1, c1)));
5499                         tabular.setCellInset(r2, c2, inset);
5500                         // FIXME?: why do we need to do this explicitly? (EL)
5501                         tabular.cellInset(r2, c2)->setBuffer(tabular.buffer());
5502
5503                         // FIXME: change tracking (MG)
5504                         inset->setChange(Change(buffer().params().trackChanges ?
5505                                                 Change::INSERTED : Change::UNCHANGED));
5506                         cur.pos() = 0;
5507                 }
5508         }
5509         return true;
5510 }
5511
5512
5513 void InsetTabular::cutSelection(Cursor & cur)
5514 {
5515         if (!cur.selection())
5516                 return;
5517
5518         row_type rs, re;
5519         col_type cs, ce;
5520         getSelection(cur, rs, re, cs, ce);
5521         for (row_type r = rs; r <= re; ++r) {
5522                 for (col_type c = cs; c <= ce; ++c) {
5523                         shared_ptr<InsetTableCell> t
5524                                 = cell(tabular.cellIndex(r, c));
5525                         if (buffer().params().trackChanges)
5526                                 // FIXME: Change tracking (MG)
5527                                 t->setChange(Change(Change::DELETED));
5528                         else
5529                                 t->clear();
5530                 }
5531         }
5532
5533         // cursor position might be invalid now
5534         if (cur.pit() > cur.lastpit())
5535                 cur.pit() = cur.lastpit();
5536         if (cur.pos() > cur.lastpos())
5537                 cur.pos() = cur.lastpos();
5538         cur.clearSelection();
5539 }
5540
5541
5542 bool InsetTabular::isRightToLeft(Cursor & cur) const
5543 {
5544         LASSERT(cur.depth() > 1, /**/);
5545         Paragraph const & parentpar = cur[cur.depth() - 2].paragraph();
5546         pos_type const parentpos = cur[cur.depth() - 2].pos();
5547         return parentpar.getFontSettings(buffer().params(),
5548                                          parentpos).language()->rightToLeft();
5549 }
5550
5551
5552 docstring InsetTabular::asString(idx_type stidx, idx_type enidx, 
5553                                  bool intoInsets)
5554 {
5555         LASSERT(stidx <= enidx, return docstring());
5556         docstring retval;
5557         col_type const col1 = tabular.cellColumn(stidx);
5558         col_type const col2 = tabular.cellColumn(enidx);
5559         row_type const row1 = tabular.cellRow(stidx);
5560         row_type const row2 = tabular.cellRow(enidx);
5561         bool first = true;
5562         for (col_type col = col1; col <= col2; col++)
5563                 for (row_type row = row1; row <= row2; row++) {
5564                         if (!first)
5565                                 retval += "\n";
5566                         else
5567                                 first = false;
5568                         retval += tabular.cellInset(row, col)->asString(intoInsets);
5569                 }
5570         return retval;
5571 }
5572
5573
5574 void InsetTabular::getSelection(Cursor & cur,
5575         row_type & rs, row_type & re, col_type & cs, col_type & ce) const
5576 {
5577         CursorSlice const & beg = cur.selBegin();
5578         CursorSlice const & end = cur.selEnd();
5579         cs = tabular.cellColumn(beg.idx());
5580         ce = tabular.cellColumn(end.idx());
5581         if (cs > ce)
5582                 swap(cs, ce);
5583
5584         rs = tabular.cellRow(beg.idx());
5585         re = tabular.cellRow(end.idx());
5586         if (rs > re)
5587                 swap(rs, re);
5588 }
5589
5590
5591 Text * InsetTabular::getText(int idx) const
5592 {
5593         return size_t(idx) < nargs() ? cell(idx)->getText(0) : 0;
5594 }
5595
5596
5597 void InsetTabular::setChange(Change const & change)
5598 {
5599         for (idx_type idx = 0; idx < nargs(); ++idx)
5600                 cell(idx)->setChange(change);
5601 }
5602
5603
5604 void InsetTabular::acceptChanges()
5605 {
5606         for (idx_type idx = 0; idx < nargs(); ++idx)
5607                 cell(idx)->acceptChanges();
5608 }
5609
5610
5611 void InsetTabular::rejectChanges()
5612 {
5613         for (idx_type idx = 0; idx < nargs(); ++idx)
5614                 cell(idx)->rejectChanges();
5615 }
5616
5617
5618 bool InsetTabular::allowParagraphCustomization(idx_type cell) const
5619 {
5620         return tabular.getPWidth(cell).zero();
5621 }
5622
5623
5624 bool InsetTabular::forcePlainLayout(idx_type cell) const
5625 {
5626         return !tabular.getPWidth(cell).zero();
5627 }
5628
5629
5630 bool InsetTabular::insertPlaintextString(BufferView & bv, docstring const & buf,
5631                                      bool usePaste)
5632 {
5633         if (buf.length() <= 0)
5634                 return true;
5635
5636         col_type cols = 1;
5637         row_type rows = 1;
5638         col_type maxCols = 1;
5639         size_t const len = buf.length();
5640         size_t p = 0;
5641
5642         while (p < len &&
5643                (p = buf.find_first_of(from_ascii("\t\n"), p)) != docstring::npos) {
5644                 switch (buf[p]) {
5645                 case '\t':
5646                         ++cols;
5647                         break;
5648                 case '\n':
5649                         if (p + 1 < len)
5650                                 ++rows;
5651                         maxCols = max(cols, maxCols);
5652                         cols = 1;
5653                         break;
5654                 }
5655                 ++p;
5656         }
5657         maxCols = max(cols, maxCols);
5658         Tabular * loctab;
5659         idx_type cell = 0;
5660         col_type ocol = 0;
5661         row_type row = 0;
5662         if (usePaste) {
5663                 paste_tabular.reset(new Tabular(buffer_, rows, maxCols));
5664                 loctab = paste_tabular.get();
5665                 cols = 0;
5666                 dirtyTabularStack(true);
5667         } else {
5668                 loctab = &tabular;
5669                 cell = bv.cursor().idx();
5670                 ocol = tabular.cellColumn(cell);
5671                 row = tabular.cellRow(cell);
5672         }
5673
5674         size_t op = 0;
5675         idx_type const cells = loctab->numberofcells;
5676         p = 0;
5677         cols = ocol;
5678         rows = loctab->nrows();
5679         col_type const columns = loctab->ncols();
5680
5681         while (cell < cells && p < len && row < rows &&
5682                (p = buf.find_first_of(from_ascii("\t\n"), p)) != docstring::npos)
5683         {
5684                 if (p >= len)
5685                         break;
5686                 switch (buf[p]) {
5687                 case '\t':
5688                         // we can only set this if we are not too far right
5689                         if (cols < columns) {
5690                                 shared_ptr<InsetTableCell> inset = loctab->cellInset(cell);
5691                                 Font const font = bv.textMetrics(&inset->text()).
5692                                         displayFont(0, 0);
5693                                 inset->setText(buf.substr(op, p - op), font,
5694                                                buffer().params().trackChanges);
5695                                 ++cols;
5696                                 ++cell;
5697                         }
5698                         break;
5699                 case '\n':
5700                         // we can only set this if we are not too far right
5701                         if (cols < columns) {
5702                                 shared_ptr<InsetTableCell> inset = tabular.cellInset(cell);
5703                                 Font const font = bv.textMetrics(&inset->text()).
5704                                         displayFont(0, 0);
5705                                 inset->setText(buf.substr(op, p - op), font,
5706                                                buffer().params().trackChanges);
5707                         }
5708                         cols = ocol;
5709                         ++row;
5710                         if (row < rows)
5711                                 cell = loctab->cellIndex(row, cols);
5712                         break;
5713                 }
5714                 ++p;
5715                 op = p;
5716         }
5717         // check for the last cell if there is no trailing '\n'
5718         if (cell < cells && op < len) {
5719                 shared_ptr<InsetTableCell> inset = loctab->cellInset(cell);
5720                 Font const font = bv.textMetrics(&inset->text()).displayFont(0, 0);
5721                 inset->setText(buf.substr(op, len - op), font,
5722                         buffer().params().trackChanges);
5723         }
5724         return true;
5725 }
5726
5727
5728 void InsetTabular::addPreview(DocIterator const & inset_pos,
5729         PreviewLoader & loader) const
5730 {
5731         DocIterator cell_pos = inset_pos;
5732
5733         cell_pos.push_back(CursorSlice(*const_cast<InsetTabular *>(this)));
5734         for (row_type r = 0; r < tabular.nrows(); ++r) {
5735                 for (col_type c = 0; c < tabular.ncols(); ++c) {
5736                         cell_pos.top().idx() = tabular.cellIndex(r, c);
5737                         tabular.cellInset(r, c)->addPreview(cell_pos, loader);
5738                 }
5739         }
5740 }
5741
5742
5743 bool InsetTabular::completionSupported(Cursor const & cur) const
5744 {
5745         Cursor const & bvCur = cur.bv().cursor();
5746         if (&bvCur.inset() != this)
5747                 return false;
5748         return cur.text()->completionSupported(cur);
5749 }
5750
5751
5752 bool InsetTabular::inlineCompletionSupported(Cursor const & cur) const
5753 {
5754         return completionSupported(cur);
5755 }
5756
5757
5758 bool InsetTabular::automaticInlineCompletion() const
5759 {
5760         return lyxrc.completion_inline_text;
5761 }
5762
5763
5764 bool InsetTabular::automaticPopupCompletion() const
5765 {
5766         return lyxrc.completion_popup_text;
5767 }
5768
5769
5770 bool InsetTabular::showCompletionCursor() const
5771 {
5772         return lyxrc.completion_cursor_text;
5773 }
5774
5775
5776 CompletionList const * InsetTabular::createCompletionList(Cursor const & cur) const
5777 {
5778         return completionSupported(cur) ? cur.text()->createCompletionList(cur) : 0;
5779 }
5780
5781
5782 docstring InsetTabular::completionPrefix(Cursor const & cur) const
5783 {
5784         if (!completionSupported(cur))
5785                 return docstring();
5786         return cur.text()->completionPrefix(cur);
5787 }
5788
5789
5790 bool InsetTabular::insertCompletion(Cursor & cur, docstring const & s, bool finished)
5791 {
5792         if (!completionSupported(cur))
5793                 return false;
5794
5795         return cur.text()->insertCompletion(cur, s, finished);
5796 }
5797
5798
5799 void InsetTabular::completionPosAndDim(Cursor const & cur, int & x, int & y, 
5800                                     Dimension & dim) const
5801 {
5802         TextMetrics const & tm = cur.bv().textMetrics(cur.text());
5803         tm.completionPosAndDim(cur, x, y, dim);
5804 }
5805
5806
5807 void InsetTabular::string2params(string const & in, InsetTabular & inset)
5808 {
5809         istringstream data(in);
5810         Lexer lex;
5811         lex.setStream(data);
5812
5813         if (in.empty())
5814                 return;
5815
5816         string token;
5817         lex >> token;
5818         if (!lex || token != "tabular") {
5819                 LYXERR0("Expected arg 1 to be \"tabular\" in " << in);
5820                 return;
5821         }
5822
5823         // This is part of the inset proper that is usually swallowed
5824         // by Buffer::readInset
5825         lex >> token;
5826         if (!lex || token != "Tabular") {
5827                 LYXERR0("Expected arg 2 to be \"Tabular\" in " << in);
5828                 return;
5829         }
5830
5831         inset.read(lex);
5832 }
5833
5834
5835 string InsetTabular::params2string(InsetTabular const & inset)
5836 {
5837         ostringstream data;
5838         data << "tabular" << ' ';
5839         inset.write(data);
5840         data << "\\end_inset\n";
5841         return data.str();
5842 }
5843
5844
5845 } // namespace lyx