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