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