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