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