]> git.lyx.org Git - lyx.git/blob - src/insets/InsetTabular.cpp
Fix multicolumn output.
[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         xs << StartTag("table");
2691
2692         // It's unclear to me if we need to mess with the long table stuff. 
2693         // We can borrow that too from docbook, if so.
2694
2695         xs << StartTag("tbody");
2696         for (row_type i = 0; i < row_info.size(); ++i) {
2697                 if (isValidRow(i)) {
2698                         ret += xhtmlRow(xs, i, runparams);
2699                 }
2700         }
2701         xs << EndTag("tbody");
2702         xs << EndTag("table");
2703
2704         return ret;
2705 }
2706
2707
2708 bool Tabular::plaintextTopHLine(odocstream & os, row_type row,
2709                                    vector<unsigned int> const & clen) const
2710 {
2711         idx_type const fcell = getFirstCellInRow(row);
2712         idx_type const n = numberOfCellsInRow(fcell) + fcell;
2713         idx_type tmp = 0;
2714
2715         for (idx_type i = fcell; i < n; ++i) {
2716                 if (topLine(i)) {
2717                         ++tmp;
2718                         break;
2719                 }
2720         }
2721         if (!tmp)
2722                 return false;
2723
2724         char_type ch;
2725         for (idx_type i = fcell; i < n; ++i) {
2726                 if (topLine(i)) {
2727                         if (leftLine(i))
2728                                 os << "+-";
2729                         else
2730                                 os << "--";
2731                         ch = '-';
2732                 } else {
2733                         os << "  ";
2734                         ch = ' ';
2735                 }
2736                 col_type column = cellColumn(i);
2737                 int len = clen[column];
2738                 while (column < column_info.size() - 1
2739                        && isPartOfMultiColumn(row, ++column))
2740                         len += clen[column] + 4;
2741                 os << docstring(len, ch);
2742                 if (topLine(i)) {
2743                         if (rightLine(i))
2744                                 os << "-+";
2745                         else
2746                                 os << "--";
2747                 } else {
2748                         os << "  ";
2749                 }
2750         }
2751         os << endl;
2752         return true;
2753 }
2754
2755
2756 bool Tabular::plaintextBottomHLine(odocstream & os, row_type row,
2757                                       vector<unsigned int> const & clen) const
2758 {
2759         idx_type const fcell = getFirstCellInRow(row);
2760         idx_type const n = numberOfCellsInRow(fcell) + fcell;
2761         idx_type tmp = 0;
2762
2763         for (idx_type i = fcell; i < n; ++i) {
2764                 if (bottomLine(i)) {
2765                         ++tmp;
2766                         break;
2767                 }
2768         }
2769         if (!tmp)
2770                 return false;
2771
2772         char_type ch;
2773         for (idx_type i = fcell; i < n; ++i) {
2774                 if (bottomLine(i)) {
2775                         if (leftLine(i))
2776                                 os << "+-";
2777                         else
2778                                 os << "--";
2779                         ch = '-';
2780                 } else {
2781                         os << "  ";
2782                         ch = ' ';
2783                 }
2784                 col_type column = cellColumn(i);
2785                 int len = clen[column];
2786                 while (column < column_info.size() -1
2787                        && isPartOfMultiColumn(row, ++column))
2788                         len += clen[column] + 4;
2789                 os << docstring(len, ch);
2790                 if (bottomLine(i)) {
2791                         if (rightLine(i))
2792                                 os << "-+";
2793                         else
2794                                 os << "--";
2795                 } else {
2796                         os << "  ";
2797                 }
2798         }
2799         os << endl;
2800         return true;
2801 }
2802
2803
2804 void Tabular::plaintextPrintCell(odocstream & os,
2805                                OutputParams const & runparams,
2806                                idx_type cell, row_type row, col_type column,
2807                                vector<unsigned int> const & clen,
2808                                bool onlydata) const
2809 {
2810         odocstringstream sstr;
2811         cellInset(cell)->plaintext(sstr, runparams);
2812
2813         if (onlydata) {
2814                 os << sstr.str();
2815                 return;
2816         }
2817
2818         if (leftLine(cell))
2819                 os << "| ";
2820         else
2821                 os << "  ";
2822
2823         unsigned int len1 = sstr.str().length();
2824         unsigned int len2 = clen[column];
2825         while (column < column_info.size() -1
2826                && isPartOfMultiColumn(row, ++column))
2827                 len2 += clen[column] + 4;
2828         len2 -= len1;
2829
2830         switch (getAlignment(cell)) {
2831         default:
2832         case LYX_ALIGN_LEFT:
2833                 len1 = 0;
2834                 break;
2835         case LYX_ALIGN_RIGHT:
2836                 len1 = len2;
2837                 len2 = 0;
2838                 break;
2839         case LYX_ALIGN_CENTER:
2840                 len1 = len2 / 2;
2841                 len2 -= len1;
2842                 break;
2843         }
2844
2845         os << docstring(len1, ' ') << sstr.str()
2846            << docstring(len2, ' ');
2847
2848         if (rightLine(cell))
2849                 os << " |";
2850         else
2851                 os << "  ";
2852 }
2853
2854
2855 void Tabular::plaintext(odocstream & os,
2856                            OutputParams const & runparams, int const depth,
2857                            bool onlydata, char_type delim) const
2858 {
2859         // first calculate the width of the single columns
2860         vector<unsigned int> clen(column_info.size());
2861
2862         if (!onlydata) {
2863                 // first all non (real) multicolumn cells!
2864                 for (col_type j = 0; j < column_info.size(); ++j) {
2865                         clen[j] = 0;
2866                         for (row_type i = 0; i < row_info.size(); ++i) {
2867                                 idx_type cell = cellIndex(i, j);
2868                                 if (isMultiColumnReal(cell))
2869                                         continue;
2870                                 odocstringstream sstr;
2871                                 cellInset(cell)->plaintext(sstr, runparams);
2872                                 if (clen[j] < sstr.str().length())
2873                                         clen[j] = sstr.str().length();
2874                         }
2875                 }
2876                 // then all (real) multicolumn cells!
2877                 for (col_type j = 0; j < column_info.size(); ++j) {
2878                         for (row_type i = 0; i < row_info.size(); ++i) {
2879                                 idx_type cell = cellIndex(i, j);
2880                                 if (!isMultiColumnReal(cell) || isPartOfMultiColumn(i, j))
2881                                         continue;
2882                                 odocstringstream sstr;
2883                                 cellInset(cell)->plaintext(sstr, runparams);
2884                                 int len = int(sstr.str().length());
2885                                 idx_type const n = columnSpan(cell);
2886                                 for (col_type k = j; len > 0 && k < j + n - 1; ++k)
2887                                         len -= clen[k];
2888                                 if (len > int(clen[j + n - 1]))
2889                                         clen[j + n - 1] = len;
2890                         }
2891                 }
2892         }
2893         idx_type cell = 0;
2894         for (row_type i = 0; i < row_info.size(); ++i) {
2895                 if (!onlydata && plaintextTopHLine(os, i, clen))
2896                         os << docstring(depth * 2, ' ');
2897                 for (col_type j = 0; j < column_info.size(); ++j) {
2898                         if (isPartOfMultiColumn(i, j))
2899                                 continue;
2900                         if (onlydata && j > 0)
2901                                 // we don't use operator<< for single UCS4 character.
2902                                 // see explanation in docstream.h
2903                                 os.put(delim);
2904                         plaintextPrintCell(os, runparams, cell, i, j, clen, onlydata);
2905                         ++cell;
2906                 }
2907                 os << endl;
2908                 if (!onlydata) {
2909                         os << docstring(depth * 2, ' ');
2910                         if (plaintextBottomHLine(os, i, clen))
2911                                 os << docstring(depth * 2, ' ');
2912                 }
2913         }
2914 }
2915
2916
2917 shared_ptr<InsetTableCell> Tabular::cellInset(idx_type cell) const
2918 {
2919         return cell_info[cellRow(cell)][cellColumn(cell)].inset;
2920 }
2921
2922
2923 shared_ptr<InsetTableCell> Tabular::cellInset(row_type row,
2924                                                col_type column) const
2925 {
2926         return cell_info[row][column].inset;
2927 }
2928
2929
2930 void Tabular::setCellInset(row_type row, col_type column,
2931                               shared_ptr<InsetTableCell> ins) const
2932 {
2933         CellData & cd = cell_info[row][column];
2934         cd.inset = ins;
2935 }
2936
2937
2938 void Tabular::validate(LaTeXFeatures & features) const
2939 {
2940         features.require("NeedTabularnewline");
2941         if (use_booktabs)
2942                 features.require("booktabs");
2943         if (is_long_tabular)
2944                 features.require("longtable");
2945         if (needRotating())
2946                 features.require("rotating");
2947         for (idx_type cell = 0; cell < numberofcells; ++cell) {
2948                 if (getVAlignment(cell) != LYX_VALIGN_TOP
2949                     || !getPWidth(cell).zero())
2950                         features.require("array");
2951                 cellInset(cell)->validate(features);
2952         }
2953 }
2954
2955
2956 Tabular::BoxType Tabular::useParbox(idx_type cell) const
2957 {
2958         ParagraphList const & parlist = cellInset(cell)->paragraphs();
2959         ParagraphList::const_iterator cit = parlist.begin();
2960         ParagraphList::const_iterator end = parlist.end();
2961
2962         for (; cit != end; ++cit)
2963                 for (int i = 0; i < cit->size(); ++i)
2964                         if (cit->isNewline(i))
2965                                 return BOX_PARBOX;
2966
2967         return BOX_NONE;
2968 }
2969
2970
2971 /////////////////////////////////////////////////////////////////////
2972 //
2973 // InsetTableCell
2974 //
2975 /////////////////////////////////////////////////////////////////////
2976
2977 InsetTableCell::InsetTableCell(Buffer * buf)
2978         : InsetText(buf, InsetText::PlainLayout), isFixedWidth(false),
2979           contentAlign(LYX_ALIGN_CENTER)
2980 {}
2981
2982
2983 bool InsetTableCell::forcePlainLayout(idx_type) const
2984 {
2985         return !isFixedWidth;
2986 }
2987
2988
2989 bool InsetTableCell::allowParagraphCustomization(idx_type) const
2990 {
2991         return isFixedWidth;
2992 }
2993
2994
2995 bool InsetTableCell::getStatus(Cursor & cur, FuncRequest const & cmd,
2996         FuncStatus & status) const
2997 {
2998         bool enabled;
2999         switch (cmd.action) {
3000         case LFUN_LAYOUT:
3001                 enabled = !forcePlainLayout();
3002                 break;
3003         case LFUN_LAYOUT_PARAGRAPH:
3004                 enabled = allowParagraphCustomization();
3005                 break;
3006         default:
3007                 return InsetText::getStatus(cur, cmd, status);
3008         }
3009         status.setEnabled(enabled);
3010         return true;
3011 }
3012
3013 docstring InsetTableCell::asString(bool intoInsets) 
3014 {
3015         docstring retval;
3016         if (paragraphs().empty())
3017                 return retval;
3018         ParagraphList::const_iterator it = paragraphs().begin();
3019         ParagraphList::const_iterator en = paragraphs().end();
3020         bool first = true;
3021         for (; it != en; ++it) {
3022                 if (!first)
3023                         retval += "\n";
3024                 else
3025                         first = false;
3026                 retval += it->asString(intoInsets ? AS_STR_INSETS : AS_STR_NONE);
3027         }
3028         return retval;
3029 }
3030
3031
3032 docstring InsetTableCell::xhtml(XHTMLStream & xs, OutputParams const & rp) const
3033 {
3034         if (!isFixedWidth)
3035                 return InsetText::insetAsXHTML(xs, rp, InsetText::JustText);
3036         return InsetText::xhtml(xs, rp);
3037 }
3038
3039
3040
3041 /////////////////////////////////////////////////////////////////////
3042 //
3043 // InsetTabular
3044 //
3045 /////////////////////////////////////////////////////////////////////
3046
3047 InsetTabular::InsetTabular(Buffer * buf, row_type rows,
3048                            col_type columns)
3049         : Inset(buf), tabular(buf, max(rows, row_type(1)), max(columns, col_type(1))), scx_(0), 
3050         rowselect_(false), colselect_(false)
3051 {
3052 }
3053
3054
3055 InsetTabular::InsetTabular(InsetTabular const & tab)
3056         : Inset(tab), tabular(tab.tabular),  scx_(0)
3057 {
3058 }
3059
3060
3061 InsetTabular::~InsetTabular()
3062 {
3063         hideDialogs("tabular", this);
3064 }
3065
3066
3067 void InsetTabular::setBuffer(Buffer & buf)
3068 {
3069         tabular.setBuffer(buf);
3070         Inset::setBuffer(buf);
3071 }
3072
3073
3074 bool InsetTabular::insetAllowed(InsetCode code) const
3075 {
3076         if (code == MATHMACRO_CODE
3077                 || (code == CAPTION_CODE && !tabular.is_long_tabular))
3078                 return false;
3079
3080         return true;
3081 }
3082
3083
3084 void InsetTabular::write(ostream & os) const
3085 {
3086         os << "Tabular" << endl;
3087         tabular.write(os);
3088 }
3089
3090
3091 docstring InsetTabular::contextMenu(BufferView const &, int, int) const
3092 {
3093         // FIXME: depending on the selection state, we could offer a different menu.
3094         return from_ascii("context-tabular");
3095 }
3096
3097
3098 void InsetTabular::read(Lexer & lex)
3099 {
3100         //bool const old_format = (lex.getString() == "\\LyXTable");
3101
3102         tabular.read(lex);
3103
3104         //if (old_format)
3105         //      return;
3106
3107         lex.next();
3108         string token = lex.getString();
3109         while (lex && token != "\\end_inset") {
3110                 lex.next();
3111                 token = lex.getString();
3112         }
3113         if (!lex)
3114                 lex.printError("Missing \\end_inset at this point. ");
3115 }
3116
3117
3118 int InsetTabular::rowFromY(Cursor & cur, int y) const
3119 {
3120         // top y coordinate of tabular
3121         int h = yo(cur.bv()) - tabular.rowAscent(0);
3122         size_t nrows = tabular.row_info.size();
3123         row_type r = 0;
3124         for (; r < nrows && y > h; ++r) {
3125                 h += tabular.rowAscent(r);
3126                 h += tabular.rowDescent(r);
3127                 h += tabular.getAdditionalHeight(r);
3128         }
3129         return r - 1;
3130 }
3131
3132
3133 int InsetTabular::columnFromX(Cursor & cur, int x) const
3134 {
3135         // left x coordinate of tabular
3136         int w = xo(cur.bv()) + ADD_TO_TABULAR_WIDTH;
3137         size_t ncols = tabular.column_info.size();
3138         col_type c = 0;
3139         for (; c < ncols && x > w; ++c)
3140                 w += tabular.columnWidth(c);
3141         return c - 1;
3142 }
3143
3144
3145 void InsetTabular::metrics(MetricsInfo & mi, Dimension & dim) const
3146 {
3147         //lyxerr << "InsetTabular::metrics: " << mi.base.bv << " width: " <<
3148         //      mi.base.textwidth << "\n";
3149         if (!mi.base.bv) {
3150                 LYXERR0("need bv");
3151                 LASSERT(false, /**/);
3152         }
3153
3154         row_type i = 0;
3155         for (idx_type cell = 0; i < tabular.row_info.size(); ++i) {
3156                 int maxAsc = 0;
3157                 int maxDesc = 0;
3158                 for (col_type j = 0; j < tabular.column_info.size(); ++j) {
3159                         if (tabular.isPartOfMultiColumn(i, j))
3160                                 // Multicolumn cell, but not first one
3161                                 continue;
3162                         Dimension dim;
3163                         MetricsInfo m = mi;
3164                         Length p_width;
3165                         if (tabular.cell_info[i][j].multicolumn ==
3166                                 Tabular::CELL_BEGIN_OF_MULTICOLUMN)
3167                                 p_width = tabular.cellInfo(cell).p_width;
3168                         else
3169                                 p_width = tabular.column_info[j].p_width;
3170                         if (!p_width.zero())
3171                                 m.base.textwidth = p_width.inPixels(mi.base.textwidth);
3172                         tabular.cellInset(cell)->metrics(m, dim);
3173                         if (!p_width.zero())
3174                                 dim.wid = m.base.textwidth;
3175                         tabular.setCellWidth(cell, dim.wid);
3176                         maxAsc  = max(maxAsc, dim.asc);
3177                         maxDesc = max(maxDesc, dim.des);
3178                         ++cell;
3179                 }
3180                 int const top_space = tabular.row_info[i].top_space_default ?
3181                         default_line_space :
3182                         tabular.row_info[i].top_space.inPixels(mi.base.textwidth);
3183                 tabular.setRowAscent(i, maxAsc + ADD_TO_HEIGHT + top_space);
3184                 int const bottom_space = tabular.row_info[i].bottom_space_default ?
3185                         default_line_space :
3186                         tabular.row_info[i].bottom_space.inPixels(mi.base.textwidth);
3187                 tabular.setRowDescent(i, maxDesc + ADD_TO_HEIGHT + bottom_space);
3188         }
3189         tabular.updateColumnWidths();
3190         dim.asc = tabular.rowAscent(0);
3191         dim.des = tabular.height() - dim.asc;
3192         dim.wid = tabular.width() + 2 * ADD_TO_TABULAR_WIDTH;
3193 }
3194
3195 bool InsetTabular::isCellSelected(Cursor & cur, row_type row, col_type col) 
3196         const
3197 {
3198         if (&cur.inset() == this && cur.selection()) {
3199                 if (cur.selIsMultiCell()) {
3200                         row_type rs, re;
3201                         col_type cs, ce;
3202                         getSelection(cur, rs, re, cs, ce);
3203                         
3204                         if (col >= cs && col <= ce && row >= rs && row <= re)
3205                                 return true;
3206                 } else 
3207                         if (col == tabular.cellColumn(cur.idx()) 
3208                                 && row == tabular.cellRow(cur.idx())) {
3209                         CursorSlice const & beg = cur.selBegin();
3210                         CursorSlice const & end = cur.selEnd();
3211
3212                         if ((end.lastpos() > 0 || end.lastpit() > 0)
3213                                   && end.pos() == end.lastpos() && beg.pos() == 0
3214                                   && end.pit() == end.lastpit() && beg.pit() == 0)
3215                                 return true;
3216                 }
3217         }
3218         return false;
3219 }
3220
3221
3222 void InsetTabular::draw(PainterInfo & pi, int x, int y) const
3223 {
3224         //lyxerr << "InsetTabular::draw: " << x << " " << y << endl;
3225         BufferView * bv = pi.base.bv;
3226         Cursor & cur = pi.base.bv->cursor();
3227
3228         // FIXME: As the full background is painted in drawSelection(),
3229         // we have no choice but to do a full repaint for the Text cells.
3230         pi.full_repaint = true;
3231
3232         resetPos(bv->cursor());
3233
3234         x += scx_;
3235         x += ADD_TO_TABULAR_WIDTH;
3236
3237         bool const original_drawing_state = pi.pain.isDrawingEnabled();
3238         bool const original_selection_state = pi.selected;
3239
3240         idx_type idx = 0;
3241         first_visible_cell = Tabular::npos;
3242         for (row_type i = 0; i < tabular.row_info.size(); ++i) {
3243                 int nx = x;
3244                 int const a = tabular.rowAscent(i);
3245                 int const d = tabular.rowDescent(i);
3246                 idx = tabular.cellIndex(i, 0);
3247                 for (col_type j = 0; j < tabular.column_info.size(); ++j) {
3248                         if (tabular.isPartOfMultiColumn(i, j))
3249                                 continue;
3250                         if (first_visible_cell == Tabular::npos)
3251                                 first_visible_cell = idx;
3252
3253                         pi.selected |= isCellSelected(cur, i, j);
3254                         int const cx = nx + tabular.getBeginningOfTextInCell(idx);
3255                         // Cache the Inset position.
3256                         bv->coordCache().insets().add(cell(idx).get(), cx, y);
3257                         if (nx + tabular.columnWidth(idx) < 0
3258                             || nx > bv->workWidth()
3259                             || y + d < 0
3260                             || y - a > bv->workHeight()) {
3261                                 pi.pain.setDrawingEnabled(false);
3262                                 cell(idx)->draw(pi, cx, y);
3263                                 drawCellLines(pi.pain, nx, y, i, idx, pi.change_);
3264                                 pi.pain.setDrawingEnabled(original_drawing_state);
3265                         } else {
3266                                 cell(idx)->draw(pi, cx, y);
3267                                 drawCellLines(pi.pain, nx, y, i, idx, pi.change_);
3268                         }
3269                         nx += tabular.columnWidth(idx);
3270                         ++idx;
3271                         pi.selected = original_selection_state;
3272                 }
3273
3274                 if (i + 1 < tabular.row_info.size())
3275                         y += d + tabular.rowAscent(i + 1) +
3276                                 tabular.getAdditionalHeight(i + 1);
3277         }
3278 }
3279
3280
3281 void InsetTabular::drawSelection(PainterInfo & pi, int x, int y) const
3282 {
3283         Cursor & cur = pi.base.bv->cursor();
3284         resetPos(cur);
3285
3286         x += scx_ + ADD_TO_TABULAR_WIDTH;
3287
3288         // FIXME: it is wrong to completely paint the background
3289         // if we want to do single row painting.
3290
3291         // Paint background of current tabular
3292         int const w = tabular.width();
3293         int const h = tabular.height();
3294         int yy = y - tabular.rowAscent(0);
3295         pi.pain.fillRectangle(x, yy, w, h, pi.backgroundColor(this));
3296
3297         if (!cur.selection())
3298                 return;
3299         if (&cur.inset() != this)
3300                 return;
3301
3302         //resetPos(cur);
3303
3304         bool const full_cell_selected = isCellSelected(cur,
3305                 tabular.cellRow(cur.idx()), tabular.cellColumn(cur.idx()));
3306
3307         if (cur.selIsMultiCell() || full_cell_selected) {
3308                 y -= tabular.rowAscent(0);
3309                 for (row_type j = 0; j < tabular.row_info.size(); ++j) {
3310                         int const a = tabular.rowAscent(j);
3311                         int const h = a + tabular.rowDescent(j);
3312                         int xx = x;
3313                         y += tabular.getAdditionalHeight(j);
3314                         for (col_type i = 0; i < tabular.column_info.size(); ++i) {
3315                                 if (tabular.isPartOfMultiColumn(j, i))
3316                                         continue;
3317                                 idx_type const cell =
3318                                         tabular.cellIndex(j, i);
3319                                 int const w = tabular.columnWidth(cell);
3320                                 if (isCellSelected(cur, j, i))
3321                                         pi.pain.fillRectangle(xx, y, w, h, Color_selection);
3322                                 xx += w;
3323                         }
3324                         y += h;
3325                 }
3326
3327         } else {
3328                 x += cellXPos(cur.idx());
3329                 x += tabular.getBeginningOfTextInCell(cur.idx());
3330                 cell(cur.idx())->drawSelection(pi, x, 0 /* ignored */);
3331         }
3332 }
3333
3334
3335 void InsetTabular::drawCellLines(Painter & pain, int x, int y,
3336                                  row_type row, idx_type cell, Change const & change) const
3337 {
3338         int x2 = x + tabular.columnWidth(cell);
3339         bool on_off = false;
3340         Color col = Color_tabularline;
3341         Color onoffcol = Color_tabularonoffline;
3342
3343         if (change.changed()) {
3344                 col = change.color();
3345                 onoffcol = change.color();
3346         }
3347
3348         if (!tabular.topAlreadyDrawn(cell)) {
3349                 on_off = !tabular.topLine(cell);
3350                 pain.line(x, y - tabular.rowAscent(row),
3351                           x2, y -  tabular.rowAscent(row),
3352                           on_off ? onoffcol : col,
3353                           on_off ? Painter::line_onoffdash : Painter::line_solid);
3354         }
3355         on_off = !tabular.bottomLine(cell);
3356         pain.line(x, y + tabular.rowDescent(row),
3357                   x2, y + tabular.rowDescent(row),
3358                   on_off ? onoffcol : col,
3359                   on_off ? Painter::line_onoffdash : Painter::line_solid);
3360         if (!tabular.leftAlreadyDrawn(cell)) {
3361                 on_off = !tabular.leftLine(cell);
3362                 pain.line(x, y -  tabular.rowAscent(row),
3363                           x, y +  tabular.rowDescent(row),
3364                           on_off ? onoffcol : col,
3365                           on_off ? Painter::line_onoffdash : Painter::line_solid);
3366         }
3367         on_off = !tabular.rightLine(cell);
3368         pain.line(x2 - tabular.getAdditionalWidth(cell),
3369                   y -  tabular.rowAscent(row),
3370                   x2 - tabular.getAdditionalWidth(cell),
3371                   y +  tabular.rowDescent(row),
3372                   on_off ? onoffcol : col,
3373                   on_off ? Painter::line_onoffdash : Painter::line_solid);
3374 }
3375
3376
3377 void InsetTabular::edit(Cursor & cur, bool front, EntryDirection)
3378 {
3379         //lyxerr << "InsetTabular::edit: " << this << endl;
3380         cur.finishUndo();
3381         cur.setSelection(false);
3382         cur.push(*this);
3383         if (front) {
3384                 if (isRightToLeft(cur))
3385                         cur.idx() = tabular.getLastCellInRow(0);
3386                 else
3387                         cur.idx() = 0;
3388                 cur.pit() = 0;
3389                 cur.pos() = 0;
3390         } else {
3391                 if (isRightToLeft(cur))
3392                         cur.idx() = tabular.getFirstCellInRow(tabular.row_info.size() - 1);
3393                 else
3394                         cur.idx() = tabular.numberofcells - 1;
3395                 cur.pit() = 0;
3396                 cur.pos() = cur.lastpos(); // FIXME crude guess
3397         }
3398         // FIXME: this accesses the position cache before it is initialized
3399         //resetPos(cur);
3400         //cur.bv().fitCursor();
3401 }
3402
3403
3404 void InsetTabular::updateLabels(ParIterator const & it, bool out)
3405 {
3406         // In a longtable, tell captions what the current float is
3407         Counters & cnts = buffer().masterBuffer()->params().documentClass().counters();
3408         string const saveflt = cnts.current_float();
3409         if (tabular.is_long_tabular)
3410                 cnts.current_float("table");
3411
3412         ParIterator it2 = it;
3413         it2.forwardPos();
3414         size_t const end = it2.nargs();
3415         for ( ; it2.idx() < end; it2.top().forwardIdx())
3416                 buffer().updateLabels(it2, out);
3417
3418         //reset afterwards
3419         if (tabular.is_long_tabular)
3420                 cnts.current_float(saveflt);
3421 }
3422
3423
3424 void InsetTabular::doDispatch(Cursor & cur, FuncRequest & cmd)
3425 {
3426         LYXERR(Debug::DEBUG, "# InsetTabular::doDispatch: cmd: " << cmd
3427                              << "\n  cur:" << cur);
3428         CursorSlice sl = cur.top();
3429         Cursor & bvcur = cur.bv().cursor();
3430
3431         switch (cmd.action) {
3432
3433         case LFUN_MOUSE_PRESS: {
3434                 //lyxerr << "# InsetTabular::MousePress\n" << cur.bv().cursor() << endl;
3435                 // select row
3436                 if (cmd.x < xo(cur.bv()) + ADD_TO_TABULAR_WIDTH
3437                         || cmd.x > xo(cur.bv()) + tabular.width()) {
3438                         row_type r = rowFromY(cur, cmd.y);
3439                         cur.idx() = tabular.getFirstCellInRow(r);
3440                         cur.pos() = 0;
3441                         cur.resetAnchor();
3442                         cur.idx() = tabular.getLastCellInRow(r);
3443                         cur.pos() = cur.lastpos();
3444                         cur.setSelection(true);
3445                         bvcur = cur; 
3446                         rowselect_ = true;
3447                         break;
3448                 }
3449                 // select column
3450                 int const y0 = yo(cur.bv()) - tabular.rowAscent(0);
3451                 if (cmd.y < y0 + ADD_TO_TABULAR_WIDTH 
3452                         || cmd.y > y0 + tabular.height()) {
3453                         col_type c = columnFromX(cur, cmd.x);
3454                         cur.idx() = tabular.cellIndex(0, c);
3455                         cur.pos() = 0;
3456                         cur.resetAnchor();
3457                         cur.idx() = tabular.cellIndex(tabular.row_info.size() - 1, c);
3458                         cur.pos() = cur.lastpos();
3459                         cur.setSelection(true);
3460                         bvcur = cur; 
3461                         colselect_ = true;
3462                         break;
3463                 }
3464                 // do not reset cursor/selection if we have selected
3465                 // some cells (bug 2715).
3466                 if (cmd.button() == mouse_button::button3
3467                     && &bvcur.selBegin().inset() == this 
3468                     && bvcur.selIsMultiCell()) 
3469                         ;
3470                 else
3471                         // Let InsetTableCell do it
3472                         cell(cur.idx())->dispatch(cur, cmd);
3473                 break;
3474         }
3475         case LFUN_MOUSE_MOTION:
3476                 //lyxerr << "# InsetTabular::MouseMotion\n" << bvcur << endl;
3477                 if (cmd.button() == mouse_button::button1) {
3478                         // only accept motions to places not deeper nested than the real anchor
3479                         if (!bvcur.anchor_.hasPart(cur)) {
3480                                 cur.undispatched();
3481                                 break;
3482                         }
3483                         // select (additional) row
3484                         if (rowselect_) {
3485                                 row_type r = rowFromY(cur, cmd.y);
3486                                 cur.idx() = tabular.getLastCellInRow(r);
3487                                 // we need to reset the cursor's pit and pos now, as the old ones
3488                                 // may no longer be valid.
3489                                 cur.pit() = 0;
3490                                 cur.pos() = 0;
3491                                 bvcur.setCursor(cur);
3492                                 bvcur.setSelection(true);
3493                                 break;
3494                         }
3495                         // select (additional) column
3496                         if (colselect_) {
3497                                 col_type c = columnFromX(cur, cmd.x);
3498                                 cur.idx() = tabular.cellIndex(tabular.row_info.size() - 1, c);
3499                                 // we need to reset the cursor's pit and pos now, as the old ones
3500                                 // may no longer be valid.
3501                                 cur.pit() = 0;
3502                                 cur.pos() = 0;
3503                                 bvcur.setCursor(cur);
3504                                 bvcur.setSelection(true);
3505                                 break;
3506                         }
3507                         // only update if selection changes
3508                         if (bvcur.idx() == cur.idx() &&
3509                                 !(bvcur.anchor_.idx() == cur.idx() && bvcur.pos() != cur.pos()))
3510                                 cur.noUpdate();
3511                         setCursorFromCoordinates(cur, cmd.x, cmd.y);
3512                         bvcur.setCursor(cur);
3513                         bvcur.setSelection(true);
3514                         // if this is a multicell selection, we just set the cursor to
3515                         // the beginning of the cell's text.
3516                         if (bvcur.selIsMultiCell()) {
3517                                 bvcur.pit() = bvcur.lastpit();
3518                                 bvcur.pos() = bvcur.lastpos();
3519                         }
3520                 }
3521                 break;
3522
3523         case LFUN_MOUSE_RELEASE:
3524                 rowselect_ = false;
3525                 colselect_ = false;
3526                 break;
3527
3528         case LFUN_CELL_BACKWARD:
3529                 movePrevCell(cur);
3530                 cur.setSelection(false);
3531                 break;
3532
3533         case LFUN_CELL_FORWARD:
3534                 moveNextCell(cur);
3535                 cur.setSelection(false);
3536                 break;
3537
3538         case LFUN_CHAR_FORWARD_SELECT:
3539         case LFUN_CHAR_FORWARD:
3540         case LFUN_CHAR_BACKWARD_SELECT:
3541         case LFUN_CHAR_BACKWARD:
3542         case LFUN_CHAR_RIGHT_SELECT:
3543         case LFUN_CHAR_RIGHT:
3544         case LFUN_CHAR_LEFT_SELECT:
3545         case LFUN_CHAR_LEFT: {
3546                 // determine whether we move to next or previous cell, where to enter 
3547                 // the new cell from, and which command to "finish" (i.e., exit the
3548                 // inset) with:
3549                 bool next_cell;
3550                 EntryDirection entry_from = ENTRY_DIRECTION_IGNORE;
3551                 FuncCode finish_lfun;
3552
3553                 if (cmd.action == LFUN_CHAR_FORWARD 
3554                                 || cmd.action == LFUN_CHAR_FORWARD_SELECT) {
3555                         next_cell = true;
3556                         finish_lfun = LFUN_FINISHED_FORWARD;
3557                 }
3558                 else if (cmd.action == LFUN_CHAR_BACKWARD
3559                                 || cmd.action == LFUN_CHAR_BACKWARD_SELECT) {
3560                         next_cell = false;
3561                         finish_lfun = LFUN_FINISHED_BACKWARD;
3562                 }
3563                 // LEFT or RIGHT commands --- the interpretation will depend on the 
3564                 // table's direction.
3565                 else {
3566                         bool const right = cmd.action == LFUN_CHAR_RIGHT
3567                                 || cmd.action == LFUN_CHAR_RIGHT_SELECT;
3568                         next_cell = isRightToLeft(cur) != right;
3569                         
3570                         if (lyxrc.visual_cursor)
3571                                 entry_from = right ? ENTRY_DIRECTION_LEFT:ENTRY_DIRECTION_RIGHT;
3572
3573                         finish_lfun = right ? LFUN_FINISHED_RIGHT : LFUN_FINISHED_LEFT;
3574                 }
3575
3576                 bool const select = cmd.action == LFUN_CHAR_FORWARD_SELECT ||
3577                     cmd.action == LFUN_CHAR_BACKWARD_SELECT ||
3578                     cmd.action == LFUN_CHAR_RIGHT_SELECT ||
3579                     cmd.action == LFUN_CHAR_LEFT_SELECT;
3580
3581                 // If we have a multicell selection or we're 
3582                 // not doing some LFUN_*_SELECT thing anyway...
3583                 if (!cur.selIsMultiCell() || !select) {
3584                         col_type const c = tabular.cellColumn(cur.idx());
3585                         row_type const r = tabular.cellRow(cur.idx());
3586                         // Are we trying to select the whole cell and is the whole cell 
3587                         // not yet selected?
3588                         bool const select_whole = select && !isCellSelected(cur, r, c) &&
3589                                 ((next_cell && cur.pit() == cur.lastpit() 
3590                                 && cur.pos() == cur.lastpos())
3591                                 || (!next_cell && cur.pit() == 0 && cur.pos() == 0));
3592
3593                         bool const empty_cell = cur.lastpos() == 0 && cur.lastpit() == 0;
3594
3595                         // ...try to dispatch to the cell's inset.
3596                         cell(cur.idx())->dispatch(cur, cmd);
3597
3598                         // When we already have a selection we want to select the whole cell
3599                         // before going to the next cell.
3600                         if (select_whole && !empty_cell){
3601                                 getText(cur.idx())->selectAll(cur);
3602                                 cur.dispatched();
3603                                 break;
3604                         }
3605
3606                         // FIXME: When we support the selection of an empty cell, remove 
3607                         // the !empty_cell from this condition. For now we jump to the next
3608                         // cell if the current cell is empty.
3609                         if (cur.result().dispatched() && !empty_cell)
3610                                 break;
3611                 }
3612
3613                 // move to next/prev cell, as appropriate
3614                 // note that we will always do this if we're selecting and we have
3615                 // a multicell selection
3616                 LYXERR(Debug::RTL, "entering " << (next_cell ? "next" : "previous")
3617                         << " cell from: " << int(entry_from));
3618                 if (next_cell)
3619                         moveNextCell(cur, entry_from);
3620                 else
3621                         movePrevCell(cur, entry_from);
3622                 // if we're exiting the table, call the appropriate FINISHED lfun
3623                 if (sl == cur.top())
3624                         cmd = FuncRequest(finish_lfun);
3625                 else
3626                         cur.dispatched();
3627                 break;
3628
3629         }
3630
3631         case LFUN_DOWN_SELECT:
3632         case LFUN_DOWN:
3633                 if (!(cur.selection() && cur.selIsMultiCell()))
3634                         cell(cur.idx())->dispatch(cur, cmd);
3635                 
3636                 cur.dispatched(); // override the cell's decision
3637                 if (sl == cur.top()) {
3638                         // if our Text didn't do anything to the cursor
3639                         // then we try to put the cursor into the cell below
3640                         // setting also the right targetX.
3641                         cur.selHandle(cmd.action == LFUN_DOWN_SELECT);
3642                         if (tabular.cellRow(cur.idx()) != tabular.row_info.size() - 1) {
3643                                 cur.idx() = tabular.cellBelow(cur.idx());
3644                                 cur.pit() = 0;
3645                                 TextMetrics const & tm =
3646                                         cur.bv().textMetrics(cell(cur.idx())->getText(0));
3647                                 cur.pos() = tm.x2pos(cur.pit(), 0, cur.targetX());
3648                         }
3649                 }
3650                 if (sl == cur.top()) {
3651                         // we trick it to go to forward after leaving the
3652                         // tabular.
3653                         cmd = FuncRequest(LFUN_FINISHED_FORWARD);
3654                         cur.undispatched();
3655                 }
3656                 if (cur.selIsMultiCell()) {
3657                         cur.pit() = cur.lastpit();
3658                         cur.pos() = cur.lastpos();
3659                         return;
3660                 }
3661                 break;
3662
3663         case LFUN_UP_SELECT:
3664         case LFUN_UP:
3665                 if (!(cur.selection() && cur.selIsMultiCell()))
3666                         cell(cur.idx())->dispatch(cur, cmd);
3667                 cur.dispatched(); // override the cell's decision
3668                 if (sl == cur.top()) {
3669                         // if our Text didn't do anything to the cursor
3670                         // then we try to put the cursor into the cell above
3671                         // setting also the right targetX.
3672                         cur.selHandle(cmd.action == LFUN_UP_SELECT);
3673                         if (tabular.cellRow(cur.idx()) != 0) {
3674                                 cur.idx() = tabular.cellAbove(cur.idx());
3675                                 cur.pit() = cur.lastpit();
3676                                 Text const * text = cell(cur.idx())->getText(0);
3677                                 TextMetrics const & tm = cur.bv().textMetrics(text);
3678                                 ParagraphMetrics const & pm =
3679                                         tm.parMetrics(cur.lastpit());
3680                                 cur.pos() = tm.x2pos(cur.pit(), pm.rows().size()-1, cur.targetX());
3681                         }
3682                 }
3683                 if (sl == cur.top()) {
3684                         cmd = FuncRequest(LFUN_UP);
3685                         cur.undispatched();
3686                 }
3687                 if (cur.selIsMultiCell()) {
3688                         cur.pit() = 0;
3689                         cur.pos() = cur.lastpos();
3690                         return;
3691                 }
3692                 break;
3693
3694 //      case LFUN_SCREEN_DOWN: {
3695 //              //if (hasSelection())
3696 //              //      cur.selection() = false;
3697 //              col_type const col = tabular.cellColumn(cur.idx());
3698 //              int const t =   cur.bv().top_y() + cur.bv().height();
3699 //              if (t < yo() + tabular.getHeightOfTabular()) {
3700 //                      cur.bv().scrollDocView(t);
3701 //                      cur.idx() = tabular.cellBelow(first_visible_cell) + col;
3702 //              } else {
3703 //                      cur.idx() = tabular.getFirstCellInRow(tabular.rows() - 1) + col;
3704 //              }
3705 //              cur.par() = 0;
3706 //              cur.pos() = 0;
3707 //              break;
3708 //      }
3709 //
3710 //      case LFUN_SCREEN_UP: {
3711 //              //if (hasSelection())
3712 //              //      cur.selection() = false;
3713 //              col_type const col = tabular.cellColumn(cur.idx());
3714 //              int const t =   cur.bv().top_y() + cur.bv().height();
3715 //              if (yo() < 0) {
3716 //                      cur.bv().scrollDocView(t);
3717 //                      if (yo() > 0)
3718 //                              cur.idx() = col;
3719 //                      else
3720 //                              cur.idx() = tabular.cellBelow(first_visible_cell) + col;
3721 //              } else {
3722 //                      cur.idx() = col;
3723 //              }
3724 //              cur.par() = cur.lastpar();
3725 //              cur.pos() = cur.lastpos();
3726 //              break;
3727 //      }
3728
3729         case LFUN_LAYOUT_TABULAR:
3730                 cur.bv().showDialog("tabular", params2string(*this), this);
3731                 break;
3732
3733         case LFUN_INSET_DIALOG_UPDATE:
3734                 cur.bv().updateDialog("tabular", params2string(*this));
3735                 break;
3736
3737         case LFUN_TABULAR_FEATURE:
3738                 if (!tabularFeatures(cur, to_utf8(cmd.argument())))
3739                         cur.undispatched();
3740                 break;
3741
3742         // insert file functions
3743         case LFUN_FILE_INSERT_PLAINTEXT_PARA:
3744         case LFUN_FILE_INSERT_PLAINTEXT:
3745                 // FIXME UNICODE
3746                 if (FileName::isAbsolute(to_utf8(cmd.argument()))) {
3747                         docstring const tmpstr = cur.bv().contentsOfPlaintextFile(
3748                                 FileName(to_utf8(cmd.argument())));
3749                         if (tmpstr.empty())
3750                                 break;
3751                         cur.recordUndoInset(INSERT_UNDO);
3752                         if (insertPlaintextString(cur.bv(), tmpstr, false)) {
3753                                 // content has been replaced,
3754                                 // so cursor might be invalid
3755                                 cur.pos() = cur.lastpos();
3756                                 cur.pit() = cur.lastpit();
3757                                 bvcur.setCursor(cur);
3758                         } else
3759                                 cur.undispatched();
3760                 }
3761                 break;
3762
3763         case LFUN_CUT:
3764                 if (cur.selIsMultiCell()) {
3765                         if (copySelection(cur)) {
3766                                 cur.recordUndoInset(DELETE_UNDO);
3767                                 cutSelection(cur);
3768                         }
3769                 } else
3770                         cell(cur.idx())->dispatch(cur, cmd);
3771                 break;
3772
3773         case LFUN_SELF_INSERT:
3774                 if (cur.selIsMultiCell()) {
3775                         cur.recordUndoInset(DELETE_UNDO);
3776                         cutSelection(cur);
3777                 }
3778                 cell(cur.idx())->dispatch(cur, cmd);
3779                 break;
3780
3781         case LFUN_CHAR_DELETE_BACKWARD:
3782         case LFUN_CHAR_DELETE_FORWARD:
3783                 if (cur.selIsMultiCell()) {
3784                         cur.recordUndoInset(DELETE_UNDO);
3785                         cutSelection(cur);
3786                 } else
3787                         cell(cur.idx())->dispatch(cur, cmd);
3788                 break;
3789
3790         case LFUN_COPY:
3791                 if (!cur.selection())
3792                         break;
3793                 if (cur.selIsMultiCell()) {
3794                         cur.finishUndo();
3795                         copySelection(cur);
3796                 } else
3797                         cell(cur.idx())->dispatch(cur, cmd);
3798                 break;
3799
3800         case LFUN_CLIPBOARD_PASTE:
3801         case LFUN_PRIMARY_SELECTION_PASTE: {
3802                 docstring const clip = (cmd.action == LFUN_CLIPBOARD_PASTE) ?
3803                         theClipboard().getAsText() :
3804                         theSelection().get();
3805                 if (clip.empty())
3806                         break;
3807                 // pass to InsertPlaintextString, but
3808                 // only if we have multi-cell content
3809                 if (clip.find_first_of(from_ascii("\t\n")) != docstring::npos) {
3810                         cur.recordUndoInset(INSERT_UNDO);
3811                         if (insertPlaintextString(cur.bv(), clip, false)) {
3812                                 // content has been replaced,
3813                                 // so cursor might be invalid
3814                                 cur.pos() = cur.lastpos();
3815                                 cur.pit() = cur.lastpit();
3816                                 bvcur.setCursor(cur);
3817                                 break;
3818                         }
3819                 }
3820                 // Let the cell handle normal text
3821                 cell(cur.idx())->dispatch(cur, cmd);
3822                 break;
3823         }
3824
3825         case LFUN_PASTE:
3826                 if (!tabularStackDirty()) {
3827                         if (!cur.selIsMultiCell())
3828                                 cell(cur.idx())->dispatch(cur, cmd);
3829                         break;
3830                 }
3831                 if (theClipboard().isInternal() ||
3832                     (!theClipboard().hasInternal() && theClipboard().hasLyXContents())) {
3833                         cur.recordUndoInset(INSERT_UNDO);
3834                         pasteClipboard(cur);
3835                 }
3836                 break;
3837
3838         case LFUN_FONT_EMPH:
3839         case LFUN_FONT_BOLD:
3840         case LFUN_FONT_BOLDSYMBOL:
3841         case LFUN_FONT_ROMAN:
3842         case LFUN_FONT_NOUN:
3843         case LFUN_FONT_ITAL:
3844         case LFUN_FONT_FRAK:
3845         case LFUN_FONT_TYPEWRITER:
3846         case LFUN_FONT_SANS:
3847         case LFUN_TEXTSTYLE_APPLY:
3848         case LFUN_TEXTSTYLE_UPDATE:
3849         case LFUN_FONT_SIZE:
3850         case LFUN_FONT_UNDERLINE:
3851         case LFUN_FONT_STRIKEOUT:
3852         case LFUN_FONT_UULINE:
3853         case LFUN_FONT_UWAVE:
3854         case LFUN_LANGUAGE:
3855         case LFUN_WORD_CAPITALIZE:
3856         case LFUN_WORD_UPCASE:
3857         case LFUN_WORD_LOWCASE:
3858         case LFUN_CHARS_TRANSPOSE:
3859                 if (cur.selIsMultiCell()) {
3860                         row_type rs, re;
3861                         col_type cs, ce;
3862                         getSelection(cur, rs, re, cs, ce);
3863                         Cursor tmpcur = cur;
3864                         for (row_type i = rs; i <= re; ++i) {
3865                                 for (col_type j = cs; j <= ce; ++j) {
3866                                         // cursor follows cell:
3867                                         tmpcur.idx() = tabular.cellIndex(i, j);
3868                                         // select this cell only:
3869                                         tmpcur.pit() = 0;
3870                                         tmpcur.pos() = 0;
3871                                         tmpcur.resetAnchor();
3872                                         tmpcur.pit() = tmpcur.lastpit();
3873                                         tmpcur.pos() = tmpcur.top().lastpos();
3874                                         tmpcur.setCursor(tmpcur);
3875                                         tmpcur.setSelection();
3876                                         cell(tmpcur.idx())->dispatch(tmpcur, cmd);
3877                                 }
3878                         }
3879                         break;
3880                 } else {
3881                         cell(cur.idx())->dispatch(cur, cmd);
3882                         break;
3883                 }
3884
3885         case LFUN_INSET_SETTINGS:
3886                 // relay this lfun to Inset, not to the cell.
3887                 Inset::doDispatch(cur, cmd);
3888                 break;
3889
3890         default:
3891                 // we try to handle this event in the insets dispatch function.
3892                 cell(cur.idx())->dispatch(cur, cmd);
3893                 break;
3894         }
3895 }
3896
3897
3898 // function sets an object as defined in func_status.h:
3899 // states OK, Unknown, Disabled, On, Off.
3900 bool InsetTabular::getStatus(Cursor & cur, FuncRequest const & cmd,
3901         FuncStatus & status) const
3902 {
3903         switch (cmd.action) {
3904         case LFUN_TABULAR_FEATURE: {
3905                 int action = Tabular::LAST_ACTION;
3906                 int i = 0;
3907                 for (; tabularFeature[i].action != Tabular::LAST_ACTION; ++i) {
3908                         string const tmp = tabularFeature[i].feature;
3909                         if (tmp == to_utf8(cmd.argument()).substr(0, tmp.length())) {
3910                                 action = tabularFeature[i].action;
3911                                 break;
3912                         }
3913                 }
3914                 if (action == Tabular::LAST_ACTION) {
3915                         status.clear();
3916                         status.unknown(true);
3917                         return true;
3918                 }
3919
3920                 string const argument
3921                         = ltrim(to_utf8(cmd.argument()).substr(tabularFeature[i].feature.length()));
3922
3923                 row_type sel_row_start = 0;
3924                 row_type sel_row_end = 0;
3925                 col_type sel_col_start = 0;
3926                 col_type sel_col_end = 0;
3927                 Tabular::ltType dummyltt;
3928                 bool flag = true;
3929
3930                 getSelection(cur, sel_row_start, sel_row_end, sel_col_start, sel_col_end);
3931
3932                 switch (action) {
3933                 case Tabular::SET_PWIDTH:
3934                 case Tabular::SET_MPWIDTH:
3935                 case Tabular::SET_SPECIAL_COLUMN:
3936                 case Tabular::SET_SPECIAL_MULTI:
3937                 case Tabular::APPEND_ROW:
3938                 case Tabular::APPEND_COLUMN:
3939                 case Tabular::DELETE_ROW:
3940                 case Tabular::DELETE_COLUMN:
3941                 case Tabular::COPY_ROW:
3942                 case Tabular::COPY_COLUMN:
3943                 case Tabular::SET_TOP_SPACE:
3944                 case Tabular::SET_BOTTOM_SPACE:
3945                 case Tabular::SET_INTERLINE_SPACE:
3946                         status.clear();
3947                         return true;
3948
3949                 case Tabular::MULTICOLUMN:
3950                         // If a row is set as longtable caption, it must not be allowed
3951                         // to unset that this row is a multicolumn.
3952                         status.setEnabled(sel_row_start == sel_row_end
3953                                 && !tabular.ltCaption(tabular.cellRow(cur.idx())));
3954                         status.setOnOff(tabular.isMultiColumn(cur.idx()));
3955                         break;
3956
3957                 case Tabular::SET_ALL_LINES:
3958                 case Tabular::UNSET_ALL_LINES:
3959                 case Tabular::SET_BORDER_LINES:
3960                         status.setEnabled(!tabular.ltCaption(tabular.cellRow(cur.idx())));
3961                         break;
3962
3963                 case Tabular::TOGGLE_LINE_TOP:
3964                         status.setEnabled(!tabular.ltCaption(tabular.cellRow(cur.idx())));
3965                         status.setOnOff(tabular.topLine(cur.idx()));
3966                         break;
3967
3968                 case Tabular::TOGGLE_LINE_BOTTOM:
3969                         status.setEnabled(!tabular.ltCaption(tabular.cellRow(cur.idx())));
3970                         status.setOnOff(tabular.bottomLine(cur.idx()));
3971                         break;
3972
3973                 case Tabular::TOGGLE_LINE_LEFT:
3974                         status.setEnabled(!tabular.ltCaption(tabular.cellRow(cur.idx())));
3975                         status.setOnOff(tabular.leftLine(cur.idx()));
3976                         break;
3977
3978                 case Tabular::TOGGLE_LINE_RIGHT:
3979                         status.setEnabled(!tabular.ltCaption(tabular.cellRow(cur.idx())));
3980                         status.setOnOff(tabular.rightLine(cur.idx()));
3981                         break;
3982
3983                 case Tabular::M_ALIGN_LEFT:
3984                         flag = false;
3985                 case Tabular::ALIGN_LEFT:
3986                         status.setOnOff(tabular.getAlignment(cur.idx(), flag) == LYX_ALIGN_LEFT);
3987                         break;
3988
3989                 case Tabular::M_ALIGN_RIGHT:
3990                         flag = false;
3991                 case Tabular::ALIGN_RIGHT:
3992                         status.setOnOff(tabular.getAlignment(cur.idx(), flag) == LYX_ALIGN_RIGHT);
3993                         break;
3994
3995                 case Tabular::M_ALIGN_CENTER:
3996                         flag = false;
3997                 case Tabular::ALIGN_CENTER:
3998                         status.setOnOff(tabular.getAlignment(cur.idx(), flag) == LYX_ALIGN_CENTER);
3999                         break;
4000
4001                 case Tabular::ALIGN_BLOCK:
4002                         status.setEnabled(!tabular.getPWidth(cur.idx()).zero());
4003                         status.setOnOff(tabular.getAlignment(cur.idx(), flag) == LYX_ALIGN_BLOCK);
4004                         break;
4005
4006                 case Tabular::M_VALIGN_TOP:
4007                         flag = false;
4008                 case Tabular::VALIGN_TOP:
4009                         status.setOnOff(
4010                                 tabular.getVAlignment(cur.idx(), flag) == Tabular::LYX_VALIGN_TOP);
4011                         break;
4012
4013                 case Tabular::M_VALIGN_BOTTOM:
4014                         flag = false;
4015                 case Tabular::VALIGN_BOTTOM:
4016                         status.setOnOff(
4017                                 tabular.getVAlignment(cur.idx(), flag) == Tabular::LYX_VALIGN_BOTTOM);
4018                         break;
4019
4020                 case Tabular::M_VALIGN_MIDDLE:
4021                         flag = false;
4022                 case Tabular::VALIGN_MIDDLE:
4023                         status.setOnOff(
4024                                 tabular.getVAlignment(cur.idx(), flag) == Tabular::LYX_VALIGN_MIDDLE);
4025                         break;
4026
4027                 case Tabular::SET_LONGTABULAR:
4028                         status.setOnOff(tabular.is_long_tabular);
4029                         break;
4030
4031                 case Tabular::UNSET_LONGTABULAR:
4032                         status.setOnOff(!tabular.is_long_tabular);
4033                         break;
4034
4035                 case Tabular::TOGGLE_ROTATE_TABULAR:
4036                 case Tabular::SET_ROTATE_TABULAR:
4037                         status.setOnOff(tabular.rotate);
4038                         break;
4039
4040                 case Tabular::TABULAR_VALIGN_TOP:
4041                         status.setOnOff(tabular.tabular_valignment 
4042                                 == Tabular::LYX_VALIGN_TOP);
4043                         break;
4044                 case Tabular::TABULAR_VALIGN_MIDDLE:
4045                         status.setOnOff(tabular.tabular_valignment 
4046                                 == Tabular::LYX_VALIGN_MIDDLE);
4047                         break;
4048                 case Tabular::TABULAR_VALIGN_BOTTOM:
4049                         status.setOnOff(tabular.tabular_valignment 
4050                                 == Tabular::LYX_VALIGN_BOTTOM);
4051                         break;
4052
4053                 case Tabular::LONGTABULAR_ALIGN_LEFT:
4054                         status.setOnOff(tabular.longtabular_alignment 
4055                                 == Tabular::LYX_LONGTABULAR_ALIGN_LEFT);
4056                         break;
4057                 case Tabular::LONGTABULAR_ALIGN_CENTER:
4058                         status.setOnOff(tabular.longtabular_alignment 
4059                                 == Tabular::LYX_LONGTABULAR_ALIGN_CENTER);
4060                         break;
4061                 case Tabular::LONGTABULAR_ALIGN_RIGHT:
4062                         status.setOnOff(tabular.longtabular_alignment 
4063                                 == Tabular::LYX_LONGTABULAR_ALIGN_RIGHT);
4064                         break;
4065
4066                 case Tabular::UNSET_ROTATE_TABULAR:
4067                         status.setOnOff(!tabular.rotate);
4068                         break;
4069
4070                 case Tabular::TOGGLE_ROTATE_CELL:
4071                 case Tabular::SET_ROTATE_CELL:
4072                         status.setOnOff(!oneCellHasRotationState(false,
4073                                 sel_row_start, sel_row_end, sel_col_start, sel_col_end));
4074                         break;
4075
4076                 case Tabular::UNSET_ROTATE_CELL:
4077                         status.setOnOff(!oneCellHasRotationState(true,
4078                                 sel_row_start, sel_row_end, sel_col_start, sel_col_end));
4079                         break;
4080
4081                 case Tabular::SET_USEBOX:
4082                         status.setOnOff(convert<int>(argument) == tabular.getUsebox(cur.idx()));
4083                         break;
4084
4085                 // every row can only be one thing:
4086                 // either a footer or header or caption
4087                 case Tabular::SET_LTFIRSTHEAD:
4088                         status.setEnabled(sel_row_start == sel_row_end
4089                                 && !tabular.ltCaption(sel_row_start));
4090                         status.setOnOff(tabular.getRowOfLTFirstHead(sel_row_start, dummyltt));
4091                         break;
4092
4093                 case Tabular::UNSET_LTFIRSTHEAD:
4094                         status.setOnOff(!tabular.getRowOfLTFirstHead(sel_row_start, dummyltt));
4095                         break;
4096
4097                 case Tabular::SET_LTHEAD:
4098                         status.setEnabled(sel_row_start == sel_row_end
4099                                 && !tabular.ltCaption(sel_row_start));
4100                         status.setOnOff(tabular.getRowOfLTHead(sel_row_start, dummyltt));
4101                         break;
4102
4103                 case Tabular::UNSET_LTHEAD:
4104                         status.setOnOff(!tabular.getRowOfLTHead(sel_row_start, dummyltt));
4105                         break;
4106
4107                 case Tabular::SET_LTFOOT:
4108                         status.setEnabled(sel_row_start == sel_row_end
4109                                 && !tabular.ltCaption(sel_row_start));
4110                         status.setOnOff(tabular.getRowOfLTFoot(sel_row_start, dummyltt));
4111                         break;
4112
4113                 case Tabular::UNSET_LTFOOT:
4114                         status.setOnOff(!tabular.getRowOfLTFoot(sel_row_start, dummyltt));
4115                         break;
4116
4117                 case Tabular::SET_LTLASTFOOT:
4118                         status.setEnabled(sel_row_start == sel_row_end
4119                                 && !tabular.ltCaption(sel_row_start));
4120                         status.setOnOff(tabular.getRowOfLTLastFoot(sel_row_start, dummyltt));
4121                         break;
4122
4123                 case Tabular::UNSET_LTLASTFOOT:
4124                         status.setOnOff(!tabular.getRowOfLTLastFoot(sel_row_start, dummyltt));
4125                         break;
4126
4127                 case Tabular::SET_LTNEWPAGE:
4128                         status.setOnOff(tabular.getLTNewPage(sel_row_start));
4129                         break;
4130
4131                 // only one row can be the caption
4132                 case Tabular::TOGGLE_LTCAPTION:
4133                         status.setEnabled(sel_row_start == sel_row_end
4134                                 && !tabular.getRowOfLTFirstHead(sel_row_start, dummyltt)
4135                                 && !tabular.getRowOfLTHead(sel_row_start, dummyltt)
4136                                 && !tabular.getRowOfLTFoot(sel_row_start, dummyltt)
4137                                 && !tabular.getRowOfLTLastFoot(sel_row_start, dummyltt)
4138                                 && (!tabular.haveLTCaption()
4139                                         || tabular.ltCaption(sel_row_start)));
4140                         status.setOnOff(tabular.ltCaption(sel_row_start));
4141                         break;
4142
4143                 case Tabular::SET_BOOKTABS:
4144                         status.setOnOff(tabular.use_booktabs);
4145                         break;
4146
4147                 case Tabular::UNSET_BOOKTABS:
4148                         status.setOnOff(!tabular.use_booktabs);
4149                         break;
4150
4151                 default:
4152                         status.clear();
4153                         status.setEnabled(false);
4154                         break;
4155                 }
4156                 return true;
4157         }
4158
4159         // These are only enabled inside tabular
4160         case LFUN_CELL_BACKWARD:
4161         case LFUN_CELL_FORWARD:
4162                 status.setEnabled(true);
4163                 return true;
4164
4165         // disable these with multiple cells selected
4166         case LFUN_INSET_INSERT:
4167         case LFUN_TABULAR_INSERT:
4168         case LFUN_FLEX_INSERT:
4169         case LFUN_FLOAT_INSERT:
4170         case LFUN_FLOAT_WIDE_INSERT:
4171         case LFUN_FOOTNOTE_INSERT:
4172         case LFUN_MARGINALNOTE_INSERT:
4173         case LFUN_MATH_INSERT:
4174         case LFUN_MATH_MODE:
4175         case LFUN_MATH_MUTATE:
4176         case LFUN_MATH_DISPLAY:
4177         case LFUN_NOTE_INSERT:
4178         case LFUN_OPTIONAL_INSERT:
4179         case LFUN_BOX_INSERT:
4180         case LFUN_BRANCH_INSERT:
4181         case LFUN_PHANTOM_INSERT:
4182         case LFUN_WRAP_INSERT:
4183         case LFUN_ERT_INSERT: {
4184                 if (cur.selIsMultiCell()) {
4185                         status.setEnabled(false);
4186                         return true;
4187                 } else
4188                         return cell(cur.idx())->getStatus(cur, cmd, status);
4189         }
4190
4191         // disable in non-fixed-width cells
4192         case LFUN_NEWLINE_INSERT:
4193         case LFUN_BREAK_PARAGRAPH: {
4194                 if (tabular.getPWidth(cur.idx()).zero()) {
4195                         status.setEnabled(false);
4196                         return true;
4197                 } else
4198                         return cell(cur.idx())->getStatus(cur, cmd, status);
4199         }
4200
4201         case LFUN_NEWPAGE_INSERT:
4202                 status.setEnabled(false);
4203                 return true;
4204
4205         case LFUN_PASTE:
4206                 if (tabularStackDirty() && theClipboard().isInternal()) {
4207                         if (cur.selIsMultiCell()) {
4208                                 row_type rs, re;
4209                                 col_type cs, ce;
4210                                 getSelection(cur, rs, re, cs, ce);
4211                                 if (paste_tabular && paste_tabular->column_info.size() == ce - cs + 1
4212                                           && paste_tabular->row_info.size() == re - rs + 1)
4213                                         status.setEnabled(true);        
4214                                 else {
4215                                         status.setEnabled(false);
4216                                         status.message(_("Selection size should match clipboard content."));
4217                                 }
4218                         } else
4219                                 status.setEnabled(true);
4220                         return true;
4221                 }
4222                 return cell(cur.idx())->getStatus(cur, cmd, status);
4223
4224         case LFUN_INSET_SETTINGS:
4225                 // relay this lfun to Inset, not to the cell.
4226                 return Inset::getStatus(cur, cmd, status);
4227
4228         case LFUN_INSET_MODIFY:
4229                 if (insetCode(cmd.getArg(0)) == TABULAR_CODE) {
4230                         status.setEnabled(true);
4231                         return true;
4232                 }
4233                 // Fall through
4234
4235         default:
4236                 // we try to handle this event in the insets dispatch function.
4237                 return cell(cur.idx())->getStatus(cur, cmd, status);
4238         }
4239 }
4240
4241
4242 Inset::DisplayType InsetTabular::display() const
4243 {
4244                 if (tabular.is_long_tabular) {
4245                         switch (tabular.longtabular_alignment) {
4246                         case Tabular::LYX_LONGTABULAR_ALIGN_LEFT:
4247                                 return AlignLeft;
4248                         case Tabular::LYX_LONGTABULAR_ALIGN_CENTER:
4249                                 return AlignCenter;
4250                         case Tabular::LYX_LONGTABULAR_ALIGN_RIGHT:
4251                                 return AlignRight;
4252                         default:
4253                                 return AlignCenter;
4254                         }
4255                 } else
4256                         return Inline;
4257 }
4258
4259
4260 int InsetTabular::latex(odocstream & os, OutputParams const & runparams) const
4261 {
4262         return tabular.latex(os, runparams);
4263 }
4264
4265
4266 int InsetTabular::plaintext(odocstream & os, OutputParams const & runparams) const
4267 {
4268         os << '\n'; // output table on a new line
4269         int const dp = runparams.linelen > 0 ? runparams.depth : 0;
4270         tabular.plaintext(os, runparams, dp, false, 0);
4271         return PLAINTEXT_NEWLINE;
4272 }
4273
4274
4275 int InsetTabular::docbook(odocstream & os, OutputParams const & runparams) const
4276 {
4277         int ret = 0;
4278         Inset * master = 0;
4279
4280         // FIXME: Why not pass a proper DocIterator here?
4281 #if 0
4282         // if the table is inside a float it doesn't need the informaltable
4283         // wrapper. Search for it.
4284         for (master = owner(); master; master = master->owner())
4285                 if (master->lyxCode() == FLOAT_CODE)
4286                         break;
4287 #endif
4288
4289         if (!master) {
4290                 os << "<informaltable>";
4291                 ++ret;
4292         }
4293         ret += tabular.docbook(os, runparams);
4294         if (!master) {
4295                 os << "</informaltable>";
4296                 ++ret;
4297         }
4298         return ret;
4299 }
4300
4301
4302 docstring InsetTabular::xhtml(XHTMLStream & xs, OutputParams const & rp) const
4303 {
4304         return tabular.xhtml(xs, rp);
4305 }
4306
4307
4308 void InsetTabular::validate(LaTeXFeatures & features) const
4309 {
4310         tabular.validate(features);
4311 }
4312
4313
4314 shared_ptr<InsetTableCell const> InsetTabular::cell(idx_type idx) const
4315 {
4316         return tabular.cellInset(idx);
4317 }
4318
4319
4320 shared_ptr<InsetTableCell> InsetTabular::cell(idx_type idx)
4321 {
4322         return tabular.cellInset(idx);
4323 }
4324
4325
4326 void InsetTabular::cursorPos(BufferView const & bv,
4327                 CursorSlice const & sl, bool boundary, int & x, int & y) const
4328 {
4329         cell(sl.idx())->cursorPos(bv, sl, boundary, x, y);
4330
4331         // y offset     correction
4332         int const row = tabular.cellRow(sl.idx());
4333         for (int i = 0; i <= row; ++i) {
4334                 if (i != 0) {
4335                         y += tabular.rowAscent(i);
4336                         y += tabular.getAdditionalHeight(i);
4337                 }
4338                 if (i != row)
4339                         y += tabular.rowDescent(i);
4340         }
4341
4342         // x offset correction
4343         int const col = tabular.cellColumn(sl.idx());
4344         int idx = tabular.cellIndex(row, 0);
4345         for (int j = 0; j < col; ++j) {
4346                 if (tabular.isPartOfMultiColumn(row, j))
4347                         continue;
4348                 x += tabular.columnWidth(idx);
4349                 ++idx;
4350         }
4351         x += tabular.getBeginningOfTextInCell(idx);
4352         x += ADD_TO_TABULAR_WIDTH;
4353         x += scx_;
4354 }
4355
4356
4357 int InsetTabular::dist(BufferView & bv, idx_type const cell, int x, int y) const
4358 {
4359         int xx = 0;
4360         int yy = 0;
4361         Inset const & inset = *tabular.cellInset(cell);
4362         Point o = bv.coordCache().getInsets().xy(&inset);
4363         int const xbeg = o.x_ - tabular.getBeginningOfTextInCell(cell);
4364         int const xend = xbeg + tabular.columnWidth(cell);
4365         row_type const row = tabular.cellRow(cell);
4366         int const ybeg = o.y_ - tabular.rowAscent(row) -
4367                          tabular.getAdditionalHeight(row);
4368         int const yend = o.y_ + tabular.rowDescent(row);
4369
4370         if (x < xbeg)
4371                 xx = xbeg - x;
4372         else if (x > xend)
4373                 xx = x - xend;
4374
4375         if (y < ybeg)
4376                 yy = ybeg - y;
4377         else if (y > yend)
4378                 yy = y - yend;
4379
4380         //lyxerr << " xbeg=" << xbeg << "  xend=" << xend
4381         //       << " ybeg=" << ybeg << " yend=" << yend
4382         //       << " xx=" << xx << " yy=" << yy
4383         //       << " dist=" << xx + yy << endl;
4384         return xx + yy;
4385 }
4386
4387
4388 Inset * InsetTabular::editXY(Cursor & cur, int x, int y)
4389 {
4390         //lyxerr << "InsetTabular::editXY: " << this << endl;
4391         cur.setSelection(false);
4392         cur.push(*this);
4393         cur.idx() = getNearestCell(cur.bv(), x, y);
4394         resetPos(cur);
4395         return cur.bv().textMetrics(&cell(cur.idx())->text()).editXY(cur, x, y);
4396 }
4397
4398
4399 void InsetTabular::setCursorFromCoordinates(Cursor & cur, int x, int y) const
4400 {
4401         cur.idx() = getNearestCell(cur.bv(), x, y);
4402         cur.bv().textMetrics(&cell(cur.idx())->text()).setCursorFromCoordinates(cur, x, y);
4403 }
4404
4405
4406 InsetTabular::idx_type InsetTabular::getNearestCell(BufferView & bv, int x, int y) const
4407 {
4408         idx_type idx_min = 0;
4409         int dist_min = numeric_limits<int>::max();
4410         for (idx_type i = 0, n = nargs(); i != n; ++i) {
4411                 if (bv.coordCache().getInsets().has(tabular.cellInset(i).get())) {
4412                         int const d = dist(bv, i, x, y);
4413                         if (d < dist_min) {
4414                                 dist_min = d;
4415                                 idx_min = i;
4416                         }
4417                 }
4418         }
4419         return idx_min;
4420 }
4421
4422
4423 int InsetTabular::cellXPos(idx_type const cell) const
4424 {
4425         idx_type c = cell;
4426
4427         for (; !tabular.isFirstCellInRow(c); --c)
4428                 ;
4429         int lx = 0;
4430         for (; c < cell; ++c)
4431                 lx += tabular.columnWidth(c);
4432
4433         return lx;
4434 }
4435
4436
4437 void InsetTabular::resetPos(Cursor & cur) const
4438 {
4439         BufferView & bv = cur.bv();
4440         int const maxwidth = bv.workWidth();
4441
4442         int const scx_old = scx_;
4443         int const i = cur.find(this);
4444         if (i == -1) {
4445                 scx_ = 0;
4446         } else {
4447                 int const X1 = 0;
4448                 int const X2 = maxwidth;
4449                 int const offset = ADD_TO_TABULAR_WIDTH + 2;
4450                 int const x1 = xo(cur.bv()) + cellXPos(cur[i].idx()) + offset;
4451                 int const x2 = x1 + tabular.columnWidth(cur[i].idx());
4452
4453                 if (x1 < X1)
4454                         scx_ = X1 + 20 - x1;
4455                 else if (x2 > X2)
4456                         scx_ = X2 - 20 - x2;
4457                 else
4458                         scx_ = 0;
4459         }
4460
4461         // only update if offset changed
4462         if (scx_ != scx_old)
4463                 cur.updateFlags(Update::Force | Update::FitCursor);
4464 }
4465
4466
4467 void InsetTabular::moveNextCell(Cursor & cur, EntryDirection entry_from)
4468 {
4469         if (isRightToLeft(cur)) {
4470                 if (tabular.isFirstCellInRow(cur.idx())) {
4471                         row_type const row = tabular.cellRow(cur.idx());
4472                         if (row == tabular.row_info.size() - 1)
4473                                 return;
4474                         cur.idx() = tabular.cellBelow(tabular.getLastCellInRow(row));
4475                 } else {
4476                         if (cur.idx() == 0)
4477                                 return;
4478                         --cur.idx();
4479                 }
4480         } else {
4481                 if (tabular.isLastCell(cur.idx()))
4482                         return;
4483                 ++cur.idx();
4484         }
4485
4486         cur.boundary(false);
4487
4488         if (cur.selIsMultiCell()) {
4489                 cur.pit() = cur.lastpit();
4490                 cur.pos() = cur.lastpos();
4491                 resetPos(cur);
4492                 return;
4493         }
4494
4495         cur.pit() = 0;
4496         cur.pos() = 0;
4497
4498         // in visual mode, place cursor at extreme left or right
4499         
4500         switch(entry_from) {
4501
4502         case ENTRY_DIRECTION_RIGHT:
4503                 cur.posVisToRowExtremity(false /* !left */);
4504                 break;
4505         case ENTRY_DIRECTION_LEFT:
4506                 cur.posVisToRowExtremity(true /* left */);
4507                 break;
4508         case ENTRY_DIRECTION_IGNORE:
4509                 // nothing to do in this case
4510                 break;
4511
4512         }
4513
4514         resetPos(cur);
4515 }
4516
4517
4518 void InsetTabular::movePrevCell(Cursor & cur, EntryDirection entry_from)
4519 {
4520         if (isRightToLeft(cur)) {
4521                 if (tabular.isLastCellInRow(cur.idx())) {
4522                         row_type const row = tabular.cellRow(cur.idx());
4523                         if (row == 0)
4524                                 return;
4525                         cur.idx() = tabular.getFirstCellInRow(row);
4526                         cur.idx() = tabular.cellAbove(cur.idx());
4527                 } else {
4528                         if (tabular.isLastCell(cur.idx()))
4529                                 return;
4530                         ++cur.idx();
4531                 }
4532         } else {
4533                 if (cur.idx() == 0) // first cell
4534                         return;
4535                 --cur.idx();
4536         }
4537
4538         if (cur.selIsMultiCell()) {
4539                 cur.pit() = cur.lastpit();
4540                 cur.pos() = cur.lastpos();
4541                 resetPos(cur);
4542                 return;
4543         }
4544
4545         cur.pit() = cur.lastpit();
4546         cur.pos() = cur.lastpos();
4547
4548         // in visual mode, place cursor at extreme left or right
4549         
4550         switch(entry_from) {
4551
4552         case ENTRY_DIRECTION_RIGHT:
4553                 cur.posVisToRowExtremity(false /* !left */);
4554                 break;
4555         case ENTRY_DIRECTION_LEFT:
4556                 cur.posVisToRowExtremity(true /* left */);
4557                 break;
4558         case ENTRY_DIRECTION_IGNORE:
4559                 // nothing to do in this case
4560                 break;
4561
4562         }
4563
4564         resetPos(cur);
4565 }
4566
4567
4568 bool InsetTabular::tabularFeatures(Cursor & cur, string const & what)
4569 {
4570         Tabular::Feature action = Tabular::LAST_ACTION;
4571
4572         int i = 0;
4573         for (; tabularFeature[i].action != Tabular::LAST_ACTION; ++i) {
4574                 string const tmp = tabularFeature[i].feature;
4575
4576                 if (tmp == what.substr(0, tmp.length())) {
4577                         //if (!compare(tabularFeatures[i].feature.c_str(), what.c_str(),
4578                         //tabularFeatures[i].feature.length()))
4579                         action = tabularFeature[i].action;
4580                         break;
4581                 }
4582         }
4583         if (action == Tabular::LAST_ACTION)
4584                 return false;
4585
4586         string const val =
4587                 ltrim(what.substr(tabularFeature[i].feature.length()));
4588         tabularFeatures(cur, action, val);
4589         return true;
4590 }
4591
4592
4593 static void checkLongtableSpecial(Tabular::ltType & ltt,
4594                           string const & special, bool & flag)
4595 {
4596         if (special == "dl_above") {
4597                 ltt.topDL = flag;
4598                 ltt.set = false;
4599         } else if (special == "dl_below") {
4600                 ltt.bottomDL = flag;
4601                 ltt.set = false;
4602         } else if (special == "empty") {
4603                 ltt.empty = flag;
4604                 ltt.set = false;
4605         } else if (flag) {
4606                 ltt.empty = false;
4607                 ltt.set = true;
4608         }
4609 }
4610
4611 bool InsetTabular::oneCellHasRotationState(bool rotated,
4612                 row_type row_start, row_type row_end,
4613                 col_type col_start, col_type col_end) const {
4614
4615         for (row_type i = row_start; i <= row_end; ++i) {
4616                 for (col_type j = col_start; j <= col_end; ++j) {
4617                         if (tabular.getRotateCell(tabular.cellIndex(i, j))
4618                                 == rotated) {
4619                                 return true;
4620                         }
4621                 }
4622         }
4623         return false;
4624 }
4625
4626 void InsetTabular::tabularFeatures(Cursor & cur,
4627         Tabular::Feature feature, string const & value)
4628 {
4629         col_type sel_col_start;
4630         col_type sel_col_end;
4631         row_type sel_row_start;
4632         row_type sel_row_end;
4633         bool setLines = false;
4634         LyXAlignment setAlign = LYX_ALIGN_LEFT;
4635         Tabular::VAlignment setVAlign = Tabular::LYX_VALIGN_TOP;
4636
4637         switch (feature) {
4638
4639         case Tabular::M_ALIGN_LEFT:
4640         case Tabular::ALIGN_LEFT:
4641                 setAlign = LYX_ALIGN_LEFT;
4642                 break;
4643
4644         case Tabular::M_ALIGN_RIGHT:
4645         case Tabular::ALIGN_RIGHT:
4646                 setAlign = LYX_ALIGN_RIGHT;
4647                 break;
4648
4649         case Tabular::M_ALIGN_CENTER:
4650         case Tabular::ALIGN_CENTER:
4651                 setAlign = LYX_ALIGN_CENTER;
4652                 break;
4653
4654         case Tabular::ALIGN_BLOCK:
4655                 setAlign = LYX_ALIGN_BLOCK;
4656                 break;
4657
4658         case Tabular::M_VALIGN_TOP:
4659         case Tabular::VALIGN_TOP:
4660                 setVAlign = Tabular::LYX_VALIGN_TOP;
4661                 break;
4662
4663         case Tabular::M_VALIGN_BOTTOM:
4664         case Tabular::VALIGN_BOTTOM:
4665                 setVAlign = Tabular::LYX_VALIGN_BOTTOM;
4666                 break;
4667
4668         case Tabular::M_VALIGN_MIDDLE:
4669         case Tabular::VALIGN_MIDDLE:
4670                 setVAlign = Tabular::LYX_VALIGN_MIDDLE;
4671                 break;
4672
4673         default:
4674                 break;
4675         }
4676
4677         cur.recordUndoInset(ATOMIC_UNDO);
4678
4679         getSelection(cur, sel_row_start, sel_row_end, sel_col_start, sel_col_end);
4680         row_type const row = tabular.cellRow(cur.idx());
4681         col_type const column = tabular.cellColumn(cur.idx());
4682         bool flag = true;
4683         Tabular::ltType ltt;
4684
4685         switch (feature) {
4686
4687         case Tabular::SET_PWIDTH: {
4688                 Length const len(value);
4689                 tabular.setColumnPWidth(cur, cur.idx(), len);
4690                 if (len.zero()
4691                     && tabular.getAlignment(cur.idx(), true) == LYX_ALIGN_BLOCK)
4692                         tabularFeatures(cur, Tabular::ALIGN_CENTER, string());
4693                 break;
4694         }
4695
4696         case Tabular::SET_MPWIDTH:
4697                 tabular.setMColumnPWidth(cur, cur.idx(), Length(value));
4698                 break;
4699
4700         case Tabular::SET_SPECIAL_COLUMN:
4701         case Tabular::SET_SPECIAL_MULTI:
4702                 tabular.setAlignSpecial(cur.idx(), from_utf8(value), feature);
4703                 break;
4704
4705         case Tabular::APPEND_ROW:
4706                 // append the row into the tabular
4707                 tabular.appendRow(cur.idx());
4708                 break;
4709
4710         case Tabular::APPEND_COLUMN:
4711                 // append the column into the tabular
4712                 tabular.appendColumn(cur.idx());
4713                 cur.idx() = tabular.cellIndex(row, column);
4714                 break;
4715
4716         case Tabular::DELETE_ROW:
4717                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4718                         tabular.deleteRow(sel_row_start);
4719                 if (sel_row_start >= tabular.row_info.size())
4720                         --sel_row_start;
4721                 cur.idx() = tabular.cellIndex(sel_row_start, column);
4722                 cur.pit() = 0;
4723                 cur.pos() = 0;
4724                 cur.setSelection(false);
4725                 break;
4726
4727         case Tabular::DELETE_COLUMN:
4728                 for (col_type i = sel_col_start; i <= sel_col_end; ++i)
4729                         tabular.deleteColumn(sel_col_start);
4730                 if (sel_col_start >= tabular.column_info.size())
4731                         --sel_col_start;
4732                 cur.idx() = tabular.cellIndex(row, sel_col_start);
4733                 cur.pit() = 0;
4734                 cur.pos() = 0;
4735                 cur.setSelection(false);
4736                 break;
4737
4738         case Tabular::COPY_ROW:
4739                 tabular.copyRow(row);
4740                 break;
4741
4742         case Tabular::COPY_COLUMN:
4743                 tabular.copyColumn(column);
4744                 cur.idx() = tabular.cellIndex(row, column);
4745                 break;
4746
4747         case Tabular::TOGGLE_LINE_TOP: {
4748                 bool lineSet = !tabular.topLine(cur.idx());
4749                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4750                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
4751                                 tabular.setTopLine(tabular.cellIndex(i, j), lineSet);
4752                 break;
4753         }
4754
4755         case Tabular::TOGGLE_LINE_BOTTOM: {
4756                 bool lineSet = !tabular.bottomLine(cur.idx());
4757                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4758                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
4759                                 tabular.setBottomLine(tabular.cellIndex(i, j), lineSet);
4760                 break;
4761         }
4762
4763         case Tabular::TOGGLE_LINE_LEFT: {
4764                 bool lineSet = !tabular.leftLine(cur.idx());
4765                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4766                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
4767                                 tabular.setLeftLine(tabular.cellIndex(i, j), lineSet);
4768                 break;
4769         }
4770
4771         case Tabular::TOGGLE_LINE_RIGHT: {
4772                 bool lineSet = !tabular.rightLine(cur.idx());
4773                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4774                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
4775                                 tabular.setRightLine(tabular.cellIndex(i, j), lineSet);
4776                 break;
4777         }
4778
4779         case Tabular::M_ALIGN_LEFT:
4780         case Tabular::M_ALIGN_RIGHT:
4781         case Tabular::M_ALIGN_CENTER:
4782                 flag = false;
4783         case Tabular::ALIGN_LEFT:
4784         case Tabular::ALIGN_RIGHT:
4785         case Tabular::ALIGN_CENTER:
4786         case Tabular::ALIGN_BLOCK:
4787                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4788                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
4789                                 tabular.setAlignment(tabular.cellIndex(i, j), setAlign, flag);
4790                 break;
4791
4792         case Tabular::M_VALIGN_TOP:
4793         case Tabular::M_VALIGN_BOTTOM:
4794         case Tabular::M_VALIGN_MIDDLE:
4795                 flag = false;
4796         case Tabular::VALIGN_TOP:
4797         case Tabular::VALIGN_BOTTOM:
4798         case Tabular::VALIGN_MIDDLE:
4799                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4800                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
4801                                 tabular.setVAlignment(tabular.cellIndex(i, j), setVAlign, flag);
4802                 break;
4803
4804         case Tabular::MULTICOLUMN: {
4805                 if (!cur.selection()) {
4806                         // just multicol for one single cell
4807                         // check whether we are completely in a multicol
4808                         if (tabular.isMultiColumn(cur.idx()))
4809                                 tabular.unsetMultiColumn(cur.idx());
4810                         else
4811                                 tabular.setMultiColumn(cur.idx(), 1);
4812                         break;
4813                 }
4814                 // we have a selection so this means we just add all this
4815                 // cells to form a multicolumn cell
4816                 idx_type const s_start = cur.selBegin().idx();
4817                 idx_type const s_end = cur.selEnd().idx();
4818                 tabular.setMultiColumn(s_start, s_end - s_start + 1);
4819                 cur.idx() = s_start;
4820                 cur.pit() = 0;
4821                 cur.pos() = 0;
4822                 cur.setSelection(false);
4823                 break;
4824         }
4825
4826         case Tabular::SET_ALL_LINES:
4827                 setLines = true;
4828         case Tabular::UNSET_ALL_LINES:
4829                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4830                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
4831                                 tabular.setAllLines(
4832                                         tabular.cellIndex(i,j), setLines);
4833                 break;
4834
4835         case Tabular::SET_BORDER_LINES:
4836                 for (row_type i = sel_row_start; i <= sel_row_end; ++i) {
4837                         tabular.setLeftLine(tabular.cellIndex(i, sel_col_start), true);
4838                         tabular.setRightLine(tabular.cellIndex(i, sel_col_end), true);
4839                 }
4840                 for (col_type j = sel_col_start; j <= sel_col_end; ++j) {
4841                         tabular.setTopLine(tabular.cellIndex(sel_row_start, j), true);
4842                         tabular.setBottomLine(tabular.cellIndex(sel_row_end, j), true);
4843                 }
4844                 break;
4845
4846         case Tabular::SET_LONGTABULAR:
4847                 tabular.is_long_tabular = true;
4848                 break;
4849
4850         case Tabular::UNSET_LONGTABULAR:
4851                 for (row_type i = 0; i < tabular.row_info.size(); ++i) {
4852                         if (tabular.ltCaption(i)) {
4853                                 cur.idx() = tabular.cellIndex(i, 0);
4854                                 cur.pit() = 0;
4855                                 cur.pos() = 0;
4856                                 tabularFeatures(cur, Tabular::TOGGLE_LTCAPTION);
4857                         }
4858                 }
4859                 tabular.is_long_tabular = false;
4860                 break;
4861
4862         case Tabular::SET_ROTATE_TABULAR:
4863                 tabular.rotate = true;
4864                 break;
4865
4866         case Tabular::UNSET_ROTATE_TABULAR:
4867                 tabular.rotate = false;
4868                 break;
4869
4870         case Tabular::TOGGLE_ROTATE_TABULAR:
4871                 tabular.rotate = !tabular.rotate;
4872                 break;
4873
4874         case Tabular::TABULAR_VALIGN_TOP:
4875                 tabular.tabular_valignment = Tabular::LYX_VALIGN_TOP;
4876                 break;
4877
4878         case Tabular::TABULAR_VALIGN_MIDDLE:
4879                 tabular.tabular_valignment = Tabular::LYX_VALIGN_MIDDLE;
4880                 break;
4881
4882         case Tabular::TABULAR_VALIGN_BOTTOM:
4883                 tabular.tabular_valignment = Tabular::LYX_VALIGN_BOTTOM;
4884                 break;
4885
4886         case Tabular::LONGTABULAR_ALIGN_LEFT:
4887                 tabular.longtabular_alignment = Tabular::LYX_LONGTABULAR_ALIGN_LEFT;
4888                 break;
4889
4890         case Tabular::LONGTABULAR_ALIGN_CENTER:
4891                 tabular.longtabular_alignment = Tabular::LYX_LONGTABULAR_ALIGN_CENTER;
4892                 break;
4893
4894         case Tabular::LONGTABULAR_ALIGN_RIGHT:
4895                 tabular.longtabular_alignment = Tabular::LYX_LONGTABULAR_ALIGN_RIGHT;
4896                 break;
4897
4898                 
4899
4900         case Tabular::SET_ROTATE_CELL:
4901                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4902                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
4903                                 tabular.setRotateCell(
4904                                         tabular.cellIndex(i, j), true);
4905                 break;
4906
4907         case Tabular::UNSET_ROTATE_CELL:
4908                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4909                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
4910                                 tabular.setRotateCell(tabular.cellIndex(i, j), false);
4911                 break;
4912
4913         case Tabular::TOGGLE_ROTATE_CELL:
4914                 {
4915                 bool oneNotRotated = oneCellHasRotationState(false,
4916                         sel_row_start, sel_row_end, sel_col_start, sel_col_end);
4917
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),
4921                                                                           oneNotRotated);
4922                 }
4923                 break;
4924
4925         case Tabular::SET_USEBOX: {
4926                 Tabular::BoxType val = Tabular::BoxType(convert<int>(value));
4927                 if (val == tabular.getUsebox(cur.idx()))
4928                         val = Tabular::BOX_NONE;
4929                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4930                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
4931                                 tabular.setUsebox(tabular.cellIndex(i, j), val);
4932                 break;
4933         }
4934
4935         case Tabular::UNSET_LTFIRSTHEAD:
4936                 flag = false;
4937         case Tabular::SET_LTFIRSTHEAD:
4938                 tabular.getRowOfLTFirstHead(row, ltt);
4939                 checkLongtableSpecial(ltt, value, flag);
4940                 tabular.setLTHead(row, flag, ltt, true);
4941                 break;
4942
4943         case Tabular::UNSET_LTHEAD:
4944                 flag = false;
4945         case Tabular::SET_LTHEAD:
4946                 tabular.getRowOfLTHead(row, ltt);
4947                 checkLongtableSpecial(ltt, value, flag);
4948                 tabular.setLTHead(row, flag, ltt, false);
4949                 break;
4950
4951         case Tabular::UNSET_LTFOOT:
4952                 flag = false;
4953         case Tabular::SET_LTFOOT:
4954                 tabular.getRowOfLTFoot(row, ltt);
4955                 checkLongtableSpecial(ltt, value, flag);
4956                 tabular.setLTFoot(row, flag, ltt, false);
4957                 break;
4958
4959         case Tabular::UNSET_LTLASTFOOT:
4960                 flag = false;
4961         case Tabular::SET_LTLASTFOOT:
4962                 tabular.getRowOfLTLastFoot(row, ltt);
4963                 checkLongtableSpecial(ltt, value, flag);
4964                 tabular.setLTFoot(row, flag, ltt, true);
4965                 break;
4966
4967         case Tabular::SET_LTNEWPAGE:
4968                 tabular.setLTNewPage(row, !tabular.getLTNewPage(row));
4969                 break;
4970
4971         case Tabular::TOGGLE_LTCAPTION: {
4972                 bool const set = !tabular.ltCaption(row);
4973                 cur.idx() = tabular.setLTCaption(row, set);
4974                 cur.pit() = 0;
4975                 cur.pos() = 0;
4976                 cur.setSelection(false);
4977
4978                 if (set) {
4979                         // When a row is set as caption, then also insert
4980                         // a caption. Otherwise the LaTeX output is broken.
4981                         lyx::dispatch(FuncRequest(LFUN_INSET_SELECT_ALL));
4982                         lyx::dispatch(FuncRequest(LFUN_CAPTION_INSERT));
4983                 } else {
4984                         FuncRequest fr(LFUN_INSET_DISSOLVE, "caption");
4985                         if (lyx::getStatus(fr).enabled())
4986                                 lyx::dispatch(fr);
4987                 }
4988                 break;
4989         }
4990
4991         case Tabular::SET_BOOKTABS:
4992                 tabular.use_booktabs = true;
4993                 break;
4994
4995         case Tabular::UNSET_BOOKTABS:
4996                 tabular.use_booktabs = false;
4997                 break;
4998
4999         case Tabular::SET_TOP_SPACE: {
5000                 Length len;
5001                 if (value == "default")
5002                         for (row_type i = sel_row_start; i <= sel_row_end; ++i)
5003                                 tabular.row_info[i].top_space_default = true;
5004                 else if (isValidLength(value, &len))
5005                         for (row_type i = sel_row_start; i <= sel_row_end; ++i) {
5006                                 tabular.row_info[i].top_space_default = false;
5007                                 tabular.row_info[i].top_space = len;
5008                         }
5009                 else
5010                         for (row_type i = sel_row_start; i <= sel_row_end; ++i) {
5011                                 tabular.row_info[i].top_space_default = false;
5012                                 tabular.row_info[i].top_space = len;
5013                         }
5014                 break;
5015         }
5016
5017         case Tabular::SET_BOTTOM_SPACE: {
5018                 Length len;
5019                 if (value == "default")
5020                         for (row_type i = sel_row_start; i <= sel_row_end; ++i)
5021                                 tabular.row_info[i].bottom_space_default = true;
5022                 else if (isValidLength(value, &len))
5023                         for (row_type i = sel_row_start; i <= sel_row_end; ++i) {
5024                                 tabular.row_info[i].bottom_space_default = false;
5025                                 tabular.row_info[i].bottom_space = len;
5026                         }
5027                 else
5028                         for (row_type i = sel_row_start; i <= sel_row_end; ++i) {
5029                                 tabular.row_info[i].bottom_space_default = false;
5030                                 tabular.row_info[i].bottom_space = len;
5031                         }
5032                 break;
5033         }
5034
5035         case Tabular::SET_INTERLINE_SPACE: {
5036                 Length len;
5037                 if (value == "default")
5038                         for (row_type i = sel_row_start; i <= sel_row_end; ++i)
5039                                 tabular.row_info[i].interline_space_default = true;
5040                 else if (isValidLength(value, &len))
5041                         for (row_type i = sel_row_start; i <= sel_row_end; ++i) {
5042                                 tabular.row_info[i].interline_space_default = false;
5043                                 tabular.row_info[i].interline_space = len;
5044                         }
5045                 else
5046                         for (row_type i = sel_row_start; i <= sel_row_end; ++i) {
5047                                 tabular.row_info[i].interline_space_default = false;
5048                                 tabular.row_info[i].interline_space = len;
5049                         }
5050                 break;
5051         }
5052
5053         // dummy stuff just to avoid warnings
5054         case Tabular::LAST_ACTION:
5055                 break;
5056         }
5057 }
5058
5059
5060 bool InsetTabular::showInsetDialog(BufferView * bv) const
5061 {
5062         bv->showDialog("tabular", params2string(*this),
5063                 const_cast<InsetTabular *>(this));
5064         return true;
5065 }
5066
5067
5068 void InsetTabular::openLayoutDialog(BufferView * bv) const
5069 {
5070         bv->showDialog("tabular", params2string(*this),
5071                 const_cast<InsetTabular *>(this));
5072 }
5073
5074
5075 bool InsetTabular::copySelection(Cursor & cur)
5076 {
5077         if (!cur.selection())
5078                 return false;
5079
5080         row_type rs, re;
5081         col_type cs, ce;
5082         getSelection(cur, rs, re, cs, ce);
5083
5084         paste_tabular.reset(new Tabular(tabular));
5085
5086         for (row_type i = 0; i < rs; ++i)
5087                 paste_tabular->deleteRow(0);
5088
5089         row_type const rows = re - rs + 1;
5090         while (paste_tabular->row_info.size() > rows)
5091                 paste_tabular->deleteRow(rows);
5092
5093         for (col_type i = 0; i < cs; ++i)
5094                 paste_tabular->deleteColumn(0);
5095
5096         col_type const columns = ce - cs + 1;
5097         while (paste_tabular->column_info.size() > columns)
5098                 paste_tabular->deleteColumn(columns);
5099
5100         paste_tabular->setBuffer(tabular.buffer());
5101
5102         odocstringstream os;
5103         OutputParams const runparams(0);
5104         paste_tabular->plaintext(os, runparams, 0, true, '\t');
5105         // Needed for the "Edit->Paste recent" menu and the system clipboard.
5106         cap::copySelection(cur, os.str());
5107
5108         // mark tabular stack dirty
5109         // FIXME: this is a workaround for bug 1919. Should be removed for 1.5,
5110         // when we (hopefully) have a one-for-all paste mechanism.
5111         // This must be called after cap::copySelection.
5112         dirtyTabularStack(true);
5113
5114         return true;
5115 }
5116
5117
5118 bool InsetTabular::pasteClipboard(Cursor & cur)
5119 {
5120         if (!paste_tabular)
5121                 return false;
5122         col_type actcol = tabular.cellColumn(cur.idx());
5123         row_type actrow = tabular.cellRow(cur.idx());
5124
5125         if (cur.selIsMultiCell()) {
5126                 row_type re;
5127                 col_type ce;
5128                 getSelection(cur, actrow, re, actcol, ce);
5129         }
5130
5131         for (row_type r1 = 0, r2 = actrow;
5132              r1 < paste_tabular->row_info.size() && r2 < tabular.row_info.size();
5133              ++r1, ++r2) {
5134                 for (col_type c1 = 0, c2 = actcol;
5135                     c1 < paste_tabular->column_info.size() && c2 < tabular.column_info.size();
5136                     ++c1, ++c2) {
5137                         if (paste_tabular->isPartOfMultiColumn(r1, c1) &&
5138                               tabular.isPartOfMultiColumn(r2, c2))
5139                                 continue;
5140                         if (paste_tabular->isPartOfMultiColumn(r1, c1)) {
5141                                 --c2;
5142                                 continue;
5143                         }
5144                         if (tabular.isPartOfMultiColumn(r2, c2)) {
5145                                 --c1;
5146                                 continue;
5147                         }
5148                         shared_ptr<InsetTableCell> inset(
5149                                 new InsetTableCell(*paste_tabular->cellInset(r1, c1)));
5150                         tabular.setCellInset(r2, c2, inset);
5151                         // FIXME: change tracking (MG)
5152                         inset->setChange(Change(buffer().params().trackChanges ?
5153                                                 Change::INSERTED : Change::UNCHANGED));
5154                         cur.pos() = 0;
5155                 }
5156         }
5157         return true;
5158 }
5159
5160
5161 void InsetTabular::cutSelection(Cursor & cur)
5162 {
5163         if (!cur.selection())
5164                 return;
5165
5166         row_type rs, re;
5167         col_type cs, ce;
5168         getSelection(cur, rs, re, cs, ce);
5169         for (row_type i = rs; i <= re; ++i) {
5170                 for (col_type j = cs; j <= ce; ++j) {
5171                         shared_ptr<InsetTableCell> t
5172                                 = cell(tabular.cellIndex(i, j));
5173                         if (buffer().params().trackChanges)
5174                                 // FIXME: Change tracking (MG)
5175                                 t->setChange(Change(Change::DELETED));
5176                         else
5177                                 t->clear();
5178                 }
5179         }
5180
5181         // cursor position might be invalid now
5182         if (cur.pit() > cur.lastpit())
5183                 cur.pit() = cur.lastpit();
5184         if (cur.pos() > cur.lastpos())
5185                 cur.pos() = cur.lastpos();
5186         cur.clearSelection();
5187 }
5188
5189
5190 bool InsetTabular::isRightToLeft(Cursor & cur) const
5191 {
5192         LASSERT(cur.depth() > 1, /**/);
5193         Paragraph const & parentpar = cur[cur.depth() - 2].paragraph();
5194         pos_type const parentpos = cur[cur.depth() - 2].pos();
5195         return parentpar.getFontSettings(buffer().params(),
5196                                          parentpos).language()->rightToLeft();
5197 }
5198
5199 docstring InsetTabular::asString(idx_type stidx, idx_type enidx, 
5200                                  bool intoInsets)
5201 {
5202         LASSERT(stidx <= enidx, return docstring());
5203         docstring retval;
5204         col_type const col1 = tabular.cellColumn(stidx);
5205         col_type const col2 = tabular.cellColumn(enidx);
5206         row_type const row1 = tabular.cellRow(stidx);
5207         row_type const row2 = tabular.cellRow(enidx);
5208         bool first = true;
5209         for (col_type col = col1; col <= col2; col++)
5210                 for (row_type row = row1; row <= row2; row++) {
5211                         if (!first)
5212                                 retval += "\n";
5213                         else
5214                                 first = false;
5215                         retval += tabular.cellInset(row, col)->asString(intoInsets);
5216                 }
5217         return retval;
5218 }
5219
5220
5221 void InsetTabular::getSelection(Cursor & cur,
5222         row_type & rs, row_type & re, col_type & cs, col_type & ce) const
5223 {
5224         CursorSlice const & beg = cur.selBegin();
5225         CursorSlice const & end = cur.selEnd();
5226         cs = tabular.cellColumn(beg.idx());
5227         ce = tabular.cellColumn(end.idx());
5228         if (cs > ce) {
5229                 ce = cs;
5230                 cs = tabular.cellColumn(end.idx());
5231         } else {
5232                 ce = tabular.cellRightColumn(end.idx());
5233         }
5234
5235         rs = tabular.cellRow(beg.idx());
5236         re = tabular.cellRow(end.idx());
5237         if (rs > re)
5238                 swap(rs, re);
5239 }
5240
5241
5242 Text * InsetTabular::getText(int idx) const
5243 {
5244         return size_t(idx) < nargs() ? cell(idx)->getText(0) : 0;
5245 }
5246
5247
5248 void InsetTabular::setChange(Change const & change)
5249 {
5250         for (idx_type idx = 0; idx < nargs(); ++idx)
5251                 cell(idx)->setChange(change);
5252 }
5253
5254
5255 void InsetTabular::acceptChanges()
5256 {
5257         for (idx_type idx = 0; idx < nargs(); ++idx)
5258                 cell(idx)->acceptChanges();
5259 }
5260
5261
5262 void InsetTabular::rejectChanges()
5263 {
5264         for (idx_type idx = 0; idx < nargs(); ++idx)
5265                 cell(idx)->rejectChanges();
5266 }
5267
5268
5269 bool InsetTabular::allowParagraphCustomization(idx_type cell) const
5270 {
5271         return tabular.getPWidth(cell).zero();
5272 }
5273
5274
5275 bool InsetTabular::forcePlainLayout(idx_type cell) const
5276 {
5277         return !tabular.getPWidth(cell).zero();
5278 }
5279
5280
5281 bool InsetTabular::insertPlaintextString(BufferView & bv, docstring const & buf,
5282                                      bool usePaste)
5283 {
5284         if (buf.length() <= 0)
5285                 return true;
5286
5287         col_type cols = 1;
5288         row_type rows = 1;
5289         col_type maxCols = 1;
5290         size_t const len = buf.length();
5291         size_t p = 0;
5292
5293         while (p < len &&
5294                (p = buf.find_first_of(from_ascii("\t\n"), p)) != docstring::npos) {
5295                 switch (buf[p]) {
5296                 case '\t':
5297                         ++cols;
5298                         break;
5299                 case '\n':
5300                         if (p + 1 < len)
5301                                 ++rows;
5302                         maxCols = max(cols, maxCols);
5303                         cols = 1;
5304                         break;
5305                 }
5306                 ++p;
5307         }
5308         maxCols = max(cols, maxCols);
5309         Tabular * loctab;
5310         idx_type cell = 0;
5311         col_type ocol = 0;
5312         row_type row = 0;
5313         if (usePaste) {
5314                 paste_tabular.reset(new Tabular(buffer_, rows, maxCols));
5315                 loctab = paste_tabular.get();
5316                 cols = 0;
5317                 dirtyTabularStack(true);
5318         } else {
5319                 loctab = &tabular;
5320                 cell = bv.cursor().idx();
5321                 ocol = tabular.cellColumn(cell);
5322                 row = tabular.cellRow(cell);
5323         }
5324
5325         size_t op = 0;
5326         idx_type const cells = loctab->numberofcells;
5327         p = 0;
5328         cols = ocol;
5329         rows = loctab->row_info.size();
5330         col_type const columns = loctab->column_info.size();
5331
5332         while (cell < cells && p < len && row < rows &&
5333                (p = buf.find_first_of(from_ascii("\t\n"), p)) != docstring::npos)
5334         {
5335                 if (p >= len)
5336                         break;
5337                 switch (buf[p]) {
5338                 case '\t':
5339                         // we can only set this if we are not too far right
5340                         if (cols < columns) {
5341                                 shared_ptr<InsetTableCell> inset = loctab->cellInset(cell);
5342                                 Font const font = bv.textMetrics(&inset->text()).
5343                                         displayFont(0, 0);
5344                                 inset->setText(buf.substr(op, p - op), font,
5345                                                buffer().params().trackChanges);
5346                                 ++cols;
5347                                 ++cell;
5348                         }
5349                         break;
5350                 case '\n':
5351                         // we can only set this if we are not too far right
5352                         if (cols < columns) {
5353                                 shared_ptr<InsetTableCell> inset = tabular.cellInset(cell);
5354                                 Font const font = bv.textMetrics(&inset->text()).
5355                                         displayFont(0, 0);
5356                                 inset->setText(buf.substr(op, p - op), font,
5357                                                buffer().params().trackChanges);
5358                         }
5359                         cols = ocol;
5360                         ++row;
5361                         if (row < rows)
5362                                 cell = loctab->cellIndex(row, cols);
5363                         break;
5364                 }
5365                 ++p;
5366                 op = p;
5367         }
5368         // check for the last cell if there is no trailing '\n'
5369         if (cell < cells && op < len) {
5370                 shared_ptr<InsetTableCell> inset = loctab->cellInset(cell);
5371                 Font const font = bv.textMetrics(&inset->text()).displayFont(0, 0);
5372                 inset->setText(buf.substr(op, len - op), font,
5373                         buffer().params().trackChanges);
5374         }
5375         return true;
5376 }
5377
5378
5379 void InsetTabular::addPreview(DocIterator const & inset_pos,
5380         PreviewLoader & loader) const
5381 {
5382         row_type const rows = tabular.row_info.size();
5383         col_type const columns = tabular.column_info.size();
5384         DocIterator cell_pos = inset_pos;
5385
5386         cell_pos.push_back(CursorSlice(*const_cast<InsetTabular *>(this)));
5387         for (row_type i = 0; i < rows; ++i) {
5388                 for (col_type j = 0; j < columns; ++j) {
5389                         cell_pos.top().idx() = tabular.cellIndex(i, j);
5390                         tabular.cellInset(i, j)->addPreview(cell_pos, loader);
5391                 }
5392         }
5393 }
5394
5395
5396 bool InsetTabular::completionSupported(Cursor const & cur) const
5397 {
5398         Cursor const & bvCur = cur.bv().cursor();
5399         if (&bvCur.inset() != this)
5400                 return false;
5401         return cur.text()->completionSupported(cur);
5402 }
5403
5404
5405 bool InsetTabular::inlineCompletionSupported(Cursor const & cur) const
5406 {
5407         return completionSupported(cur);
5408 }
5409
5410
5411 bool InsetTabular::automaticInlineCompletion() const
5412 {
5413         return lyxrc.completion_inline_text;
5414 }
5415
5416
5417 bool InsetTabular::automaticPopupCompletion() const
5418 {
5419         return lyxrc.completion_popup_text;
5420 }
5421
5422
5423 bool InsetTabular::showCompletionCursor() const
5424 {
5425         return lyxrc.completion_cursor_text;
5426 }
5427
5428
5429 CompletionList const * InsetTabular::createCompletionList(Cursor const & cur) const
5430 {
5431         return completionSupported(cur) ? cur.text()->createCompletionList(cur) : 0;
5432 }
5433
5434
5435 docstring InsetTabular::completionPrefix(Cursor const & cur) const
5436 {
5437         if (!completionSupported(cur))
5438                 return docstring();
5439         return cur.text()->completionPrefix(cur);
5440 }
5441
5442
5443 bool InsetTabular::insertCompletion(Cursor & cur, docstring const & s, bool finished)
5444 {
5445         if (!completionSupported(cur))
5446                 return false;
5447
5448         return cur.text()->insertCompletion(cur, s, finished);
5449 }
5450
5451
5452 void InsetTabular::completionPosAndDim(Cursor const & cur, int & x, int & y, 
5453                                     Dimension & dim) const
5454 {
5455         TextMetrics const & tm = cur.bv().textMetrics(cur.text());
5456         tm.completionPosAndDim(cur, x, y, dim);
5457 }
5458
5459
5460 void InsetTabular::string2params(string const & in, InsetTabular & inset)
5461 {
5462         istringstream data(in);
5463         Lexer lex;
5464         lex.setStream(data);
5465
5466         if (in.empty())
5467                 return;
5468
5469         string token;
5470         lex >> token;
5471         if (!lex || token != "tabular") {
5472                 LYXERR0("Expected arg 1 to be \"tabular\" in " << in);
5473                 return;
5474         }
5475
5476         // This is part of the inset proper that is usually swallowed
5477         // by Buffer::readInset
5478         lex >> token;
5479         if (!lex || token != "Tabular") {
5480                 LYXERR0("Expected arg 2 to be \"Tabular\" in " << in);
5481                 return;
5482         }
5483
5484         inset.read(lex);
5485 }
5486
5487
5488 string InsetTabular::params2string(InsetTabular const & inset)
5489 {
5490         ostringstream data;
5491         data << "tabular" << ' ';
5492         inset.write(data);
5493         data << "\\end_inset\n";
5494         return data.str();
5495 }
5496
5497
5498 } // namespace lyx