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