]> git.lyx.org Git - lyx.git/blob - src/insets/InsetTabular.cpp
update author settings for the files I recently notably modified
[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 "paragraph_funcs.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(const_cast<Buffer &>(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         col_type ncols = column_info.size();
807         row_type nrows = row_info.size();
808         numberofcells = 0;
809         for (row_type row = 0; row < nrows; ++row)
810                 for (col_type column = 0; column < ncols; ++column) {
811                         if (!isPartOfMultiColumn(row, column))
812                                 ++numberofcells;
813                         cell_info[row][column].cellno = numberofcells - 1;
814                 }
815
816         rowofcell.resize(numberofcells);
817         columnofcell.resize(numberofcells);
818         idx_type i = 0;
819         for (row_type row = 0; row < nrows; ++row)
820                 for (col_type column = 0; column < ncols; ++column) {
821                         if (isPartOfMultiColumn(row, column))
822                                 continue;
823                         rowofcell[i] = row;
824                         columnofcell[i] = column;
825                         setFixedWidth(row, column);
826                         updateContentAlignment(row, column);
827                         ++i;
828                 }
829 }
830
831
832 Tabular::idx_type Tabular::numberOfCellsInRow(idx_type const cell) const
833 {
834         row_type const row = cellRow(cell);
835         idx_type result = 0;
836         for (col_type i = 0; i < column_info.size(); ++i)
837                 if (cell_info[row][i].multicolumn != Tabular::CELL_PART_OF_MULTICOLUMN)
838                         ++result;
839         return result;
840 }
841
842
843 bool Tabular::topLine(idx_type const cell) const
844 {
845         return cellInfo(cell).top_line;
846 }
847
848
849 bool Tabular::bottomLine(idx_type const cell) const
850 {
851         return cellInfo(cell).bottom_line;
852 }
853
854
855 bool Tabular::leftLine(idx_type cell) const
856 {
857         if (use_booktabs)
858                 return false;
859         return cellInfo(cell).left_line;
860 }
861
862
863 bool Tabular::rightLine(idx_type cell) const
864 {
865         if (use_booktabs)
866                 return false;
867         return cellInfo(cell).right_line;
868 }
869
870
871 bool Tabular::topAlreadyDrawn(idx_type cell) const
872 {
873         row_type row = cellRow(cell);
874         if (row == 0)
875                 return false;
876         idx_type i = cellIndex(row - 1, cellColumn(cell));
877         return !rowTopLine(row) && bottomLine(i);
878 }
879
880
881 bool Tabular::leftAlreadyDrawn(idx_type cell) const
882 {
883         col_type col = cellColumn(cell);
884         if (col == 0)
885                 return false;
886         idx_type i = cellIndex(cellRow(cell), col - 1);
887         return rightLine(i) && !leftLine(cell);
888 }
889
890
891 bool Tabular::isLastRow(idx_type cell) const
892 {
893         return cellRow(cell) == row_info.size() - 1;
894 }
895
896
897 int Tabular::getAdditionalHeight(row_type row) const
898 {
899         if (!row || row >= row_info.size())
900                 return 0;
901
902         int const interline_space = row_info[row - 1].interline_space_default ?
903                 default_line_space :
904                 row_info[row - 1].interline_space.inPixels(width());
905         if (rowTopLine(row) && rowBottomLine(row - 1))
906                 return interline_space + WIDTH_OF_LINE;
907         return interline_space;
908 }
909
910
911 int Tabular::getAdditionalWidth(idx_type cell) const
912 {
913         col_type const nextcol = cellColumn(cell) + columnSpan(cell);
914         if (rightLine(cell) 
915                 && nextcol < column_info.size() && leftLine(cellIndex(cellRow(cell), nextcol)))
916                 return WIDTH_OF_LINE;
917         return 0;
918 }
919
920
921 int Tabular::columnWidth(idx_type cell) const
922 {
923         int w = 0;
924         col_type const span = columnSpan(cell);
925         col_type const col = cellColumn(cell);
926         for(col_type c = col; c < col + span ; ++c)
927                 w += column_info[c].width;
928         return w;
929 }
930
931
932 bool Tabular::updateColumnWidths()
933 {
934         col_type const ncols = column_info.size();
935         row_type const nrows = row_info.size();
936         bool update = false;
937         // for each col get max of single col cells
938         for(col_type c = 0; c < ncols; ++c) {
939                 int new_width = 0;
940                 for(row_type r = 0; r < nrows; ++r) {
941                         idx_type const i = cellIndex(r, c);
942                         if (columnSpan(i) == 1)
943                                 new_width = max(new_width, cellInfo(i).width);
944                 }
945
946                 if (column_info[c].width != new_width) {
947                         column_info[c].width = new_width;
948                         update = true;
949                 }
950         }
951         // update col widths to fit merged cells
952         for(col_type c = 0; c < ncols; ++c)
953                 for(row_type r = 0; r < nrows; ++r) {
954                         idx_type const i = cellIndex(r, c);
955                         int const span = columnSpan(i);
956                         if (span == 1 || c > cellColumn(i))
957                                 continue;
958
959                         int old_width = 0;
960                         for(col_type j = c; j < c + span ; ++j)
961                                 old_width += column_info[j].width;
962
963                         if (cellInfo(i).width > old_width) {
964                                 column_info[c + span - 1].width += cellInfo(i).width - old_width;
965                                 update = true;
966                         }
967                 }
968
969         return update;
970 }
971
972
973 int Tabular::width() const
974 {
975         col_type const ncols = column_info.size();
976         int width = 0;
977         for (col_type i = 0; i < ncols; ++i)
978                 width += column_info[i].width;
979         return width;
980 }
981
982
983 void Tabular::setCellWidth(idx_type cell, int new_width)
984 {
985         cellInfo(cell).width = new_width + 2 * WIDTH_OF_LINE 
986                 + getAdditionalWidth(cell);
987 }
988
989
990 void Tabular::setAlignment(idx_type cell, LyXAlignment align,
991                               bool onlycolumn)
992 {
993         if (!isMultiColumn(cell) || onlycolumn)
994                 column_info[cellColumn(cell)].alignment = align;
995         if (!onlycolumn)
996                 cellInfo(cell).alignment = align;
997         cellInset(cell).get()->setContentAlignment(align);
998 }
999
1000
1001 void Tabular::setVAlignment(idx_type cell, VAlignment align,
1002                                bool onlycolumn)
1003 {
1004         if (!isMultiColumn(cell) || onlycolumn)
1005                 column_info[cellColumn(cell)].valignment = align;
1006         if (!onlycolumn)
1007                 cellInfo(cell).valignment = align;
1008 }
1009
1010
1011 namespace {
1012
1013 /**
1014  * Allow line and paragraph breaks for fixed width cells or disallow them,
1015  * merge cell paragraphs and reset layout to standard for variable width
1016  * cells.
1017  */
1018 void toggleFixedWidth(Cursor & cur, InsetTableCell * inset, bool fixedWidth)
1019 {
1020         inset->setAutoBreakRows(fixedWidth);
1021         inset->toggleFixedWidth(fixedWidth);
1022         if (fixedWidth)
1023                 return;
1024
1025         // merge all paragraphs to one
1026         BufferParams const & bp = cur.bv().buffer().params();
1027         while (inset->paragraphs().size() > 1)
1028                 mergeParagraph(bp, inset->paragraphs(), 0);
1029
1030         // reset layout
1031         cur.push(*inset);
1032         // undo information has already been recorded
1033         inset->getText(0)->setLayout(cur.bv().buffer(), 0, cur.lastpit() + 1,
1034                         bp.documentClass().plainLayoutName());
1035         cur.pop();
1036 }
1037
1038 }
1039
1040
1041 void Tabular::setColumnPWidth(Cursor & cur, idx_type cell,
1042                 Length const & width)
1043 {
1044         col_type const j = cellColumn(cell);
1045
1046         column_info[j].p_width = width;
1047         for (row_type i = 0; i < row_info.size(); ++i) {
1048                 idx_type const cell = cellIndex(i, j);
1049                 // because of multicolumns
1050                 toggleFixedWidth(cur, cellInset(cell).get(),
1051                                  !getPWidth(cell).zero());
1052         }
1053         // cur paragraph can become invalid after paragraphs were merged
1054         if (cur.pit() > cur.lastpit())
1055                 cur.pit() = cur.lastpit();
1056         // cur position can become invalid after newlines were removed
1057         if (cur.pos() > cur.lastpos())
1058                 cur.pos() = cur.lastpos();
1059 }
1060
1061
1062 bool Tabular::setFixedWidth(row_type r, col_type c)
1063 {
1064         bool const multicol = cell_info[r][c].multicolumn != CELL_NORMAL;
1065         bool const fixed_width = (!column_info[c].p_width.zero() && !multicol)
1066               || (multicol && !cell_info[r][c].p_width.zero());
1067         cell_info[r][c].inset->toggleFixedWidth(fixed_width);
1068         return fixed_width;
1069 }
1070
1071
1072 void Tabular::updateContentAlignment(row_type r, col_type c)
1073 {
1074         cell_info[r][c].inset->setContentAlignment(
1075                 getAlignment(cellIndex(r, c)));
1076 }
1077
1078
1079 bool Tabular::setMColumnPWidth(Cursor & cur, idx_type cell,
1080                 Length const & width)
1081 {
1082         if (!isMultiColumn(cell))
1083                 return false;
1084
1085         cellInfo(cell).p_width = width;
1086         toggleFixedWidth(cur, cellInset(cell).get(), !width.zero());
1087         // cur paragraph can become invalid after paragraphs were merged
1088         if (cur.pit() > cur.lastpit())
1089                 cur.pit() = cur.lastpit();
1090         // cur position can become invalid after newlines were removed
1091         if (cur.pos() > cur.lastpos())
1092                 cur.pos() = cur.lastpos();
1093         return true;
1094 }
1095
1096
1097 void Tabular::setAlignSpecial(idx_type cell, docstring const & special,
1098                                  Tabular::Feature what)
1099 {
1100         if (what == SET_SPECIAL_MULTI)
1101                 cellInfo(cell).align_special = special;
1102         else
1103                 column_info[cellColumn(cell)].align_special = special;
1104 }
1105
1106
1107 void Tabular::setAllLines(idx_type cell, bool line)
1108 {
1109         setTopLine(cell, line);
1110         setBottomLine(cell, line);
1111         setRightLine(cell, line);
1112         setLeftLine(cell, line);
1113 }
1114
1115
1116 void Tabular::setTopLine(idx_type i, bool line)
1117 {
1118         cellInfo(i).top_line = line;
1119 }
1120
1121
1122 void Tabular::setBottomLine(idx_type i, bool line)
1123 {
1124         cellInfo(i).bottom_line = line;
1125 }
1126
1127
1128 void Tabular::setLeftLine(idx_type cell, bool line)
1129 {
1130         cellInfo(cell).left_line = line;
1131 }
1132
1133
1134 void Tabular::setRightLine(idx_type cell, bool line)
1135 {
1136         cellInfo(cell).right_line = line;
1137 }
1138
1139 bool Tabular::rowTopLine(row_type r) const
1140 {
1141         idx_type i0 = getFirstCellInRow(r);
1142         idx_type i1 = getLastCellInRow(r);
1143         bool all_rows_set = true;
1144         for (idx_type j = i0; all_rows_set && j <= i1; ++j)
1145                 all_rows_set = cellInfo(j).top_line;
1146         return all_rows_set;
1147 }
1148
1149
1150 bool Tabular::rowBottomLine(row_type r) const
1151 {
1152         idx_type i0 = getFirstCellInRow(r);
1153         idx_type i1 = getLastCellInRow(r);
1154         bool all_rows_set = true;
1155         for (idx_type j = i0; all_rows_set && j <= i1; ++j)
1156                 all_rows_set = cellInfo(j).bottom_line;
1157         return all_rows_set;
1158 }
1159
1160
1161 bool Tabular::columnLeftLine(col_type c) const
1162 {
1163         if (use_booktabs)
1164                 return false;
1165
1166         int nrows_left = 0;
1167         int total = 0;
1168         row_type const nrows = row_info.size();
1169         for (row_type r = 0; r < nrows; ++r) {
1170                 idx_type i = cellIndex(r, c);
1171                 if (c == cellColumn(i)) {
1172                         ++total;
1173                         bool right = c > 0 && cellInfo(cellIndex(r, c - 1)).right_line;
1174                         if (cellInfo(i).left_line || right)
1175                                 ++nrows_left;
1176                 }
1177         }
1178         return 2 * nrows_left >= total;
1179 }
1180
1181
1182 bool Tabular::columnRightLine(col_type c) const
1183 {
1184         if (use_booktabs)
1185                 return false;
1186
1187         int nrows_right = 0;
1188         int total = 0;
1189         row_type const nrows = row_info.size();
1190         for (row_type r = 0; r < nrows; ++r) {
1191                 idx_type i = cellIndex(r, c);
1192                 if (c == cellColumn(i) + columnSpan(i) - 1) {
1193                         ++total;
1194                         bool left = (c + 1 < column_info.size() 
1195                                 && cellInfo(cellIndex(r, c + 1)).left_line)
1196                                 || c + 1 == column_info.size();
1197                         if (cellInfo(i).right_line && left)
1198                                 ++nrows_right;
1199                 }
1200         }
1201         return 2 * nrows_right >= total;
1202 }
1203
1204
1205 LyXAlignment Tabular::getAlignment(idx_type cell, bool onlycolumn) const
1206 {
1207         if (!onlycolumn && isMultiColumn(cell))
1208                 return cellInfo(cell).alignment;
1209         return column_info[cellColumn(cell)].alignment;
1210 }
1211
1212
1213 Tabular::VAlignment
1214 Tabular::getVAlignment(idx_type cell, bool onlycolumn) const
1215 {
1216         if (!onlycolumn && isMultiColumn(cell))
1217                 return cellInfo(cell).valignment;
1218         return column_info[cellColumn(cell)].valignment;
1219 }
1220
1221
1222 Length const Tabular::getPWidth(idx_type cell) const
1223 {
1224         if (isMultiColumn(cell))
1225                 return cellInfo(cell).p_width;
1226         return column_info[cellColumn(cell)].p_width;
1227 }
1228
1229
1230 int Tabular::cellWidth(idx_type cell) const
1231 {
1232         return cellInfo(cell).width;
1233 }
1234
1235
1236 int Tabular::getBeginningOfTextInCell(idx_type cell) const
1237 {
1238         int x = 0;
1239
1240         switch (getAlignment(cell)) {
1241         case LYX_ALIGN_CENTER:
1242                 x += (columnWidth(cell) - cellWidth(cell)) / 2;
1243                 break;
1244         case LYX_ALIGN_RIGHT:
1245                 x += columnWidth(cell) - cellWidth(cell);
1246                 // + getAdditionalWidth(cell);
1247                 break;
1248         default:
1249                 // LYX_ALIGN_LEFT: nothing :-)
1250                 break;
1251         }
1252
1253         // the LaTeX Way :-(
1254         x += WIDTH_OF_LINE;
1255         return x;
1256 }
1257
1258
1259 bool Tabular::isFirstCellInRow(idx_type cell) const
1260 {
1261         return cellColumn(cell) == 0;
1262 }
1263
1264
1265 Tabular::idx_type Tabular::getFirstCellInRow(row_type row) const
1266 {
1267         if (row > row_info.size() - 1)
1268                 row = row_info.size() - 1;
1269         return cell_info[row][0].cellno;
1270 }
1271
1272
1273 bool Tabular::isLastCellInRow(idx_type cell) const
1274 {
1275         return cellRightColumn(cell) == column_info.size() - 1;
1276 }
1277
1278
1279 Tabular::idx_type Tabular::getLastCellInRow(row_type row) const
1280 {
1281         if (row > row_info.size() - 1)
1282                 row = row_info.size() - 1;
1283         return cell_info[row][column_info.size() - 1].cellno;
1284 }
1285
1286
1287 Tabular::row_type Tabular::cellRow(idx_type cell) const
1288 {
1289         if (cell >= numberofcells)
1290                 return row_info.size() - 1;
1291         if (cell == npos)
1292                 return 0;
1293         return rowofcell[cell];
1294 }
1295
1296
1297 Tabular::col_type Tabular::cellColumn(idx_type cell) const
1298 {
1299         if (cell >= numberofcells)
1300                 return column_info.size() - 1;
1301         if (cell == npos)
1302                 return 0;       
1303         return columnofcell[cell];
1304 }
1305
1306
1307 Tabular::col_type Tabular::cellRightColumn(idx_type cell) const
1308 {
1309         row_type const row = cellRow(cell);
1310         col_type column = cellColumn(cell);
1311         while (column < column_info.size() - 1 &&
1312                    cell_info[row][column + 1].multicolumn == CELL_PART_OF_MULTICOLUMN)
1313                 ++column;
1314         return column;
1315 }
1316
1317
1318 void Tabular::write(ostream & os) const
1319 {
1320         // header line
1321         os << "<lyxtabular"
1322            << write_attribute("version", 3)
1323            << write_attribute("rows", row_info.size())
1324            << write_attribute("columns", column_info.size())
1325            << ">\n";
1326         // global longtable options
1327         os << "<features"
1328            << write_attribute("rotate", rotate)
1329            << write_attribute("booktabs", use_booktabs)
1330            << write_attribute("islongtable", is_long_tabular)
1331            << write_attribute("firstHeadTopDL", endfirsthead.topDL)
1332            << write_attribute("firstHeadBottomDL", endfirsthead.bottomDL)
1333            << write_attribute("firstHeadEmpty", endfirsthead.empty)
1334            << write_attribute("headTopDL", endhead.topDL)
1335            << write_attribute("headBottomDL", endhead.bottomDL)
1336            << write_attribute("footTopDL", endfoot.topDL)
1337            << write_attribute("footBottomDL", endfoot.bottomDL)
1338            << write_attribute("lastFootTopDL", endlastfoot.topDL)
1339            << write_attribute("lastFootBottomDL", endlastfoot.bottomDL)
1340            << write_attribute("lastFootEmpty", endlastfoot.empty);
1341         // longtables cannot be aligned vertically
1342         if (!is_long_tabular)
1343            os << write_attribute("tabularvalignment", tabular_valignment);
1344         if (is_long_tabular)
1345            os << write_attribute("longtabularalignment",
1346                                  longtabular_alignment);
1347         os << ">\n";
1348         for (col_type j = 0; j < column_info.size(); ++j) {
1349                 os << "<column"
1350                    << write_attribute("alignment", column_info[j].alignment)
1351                    << write_attribute("valignment", column_info[j].valignment)
1352                    << write_attribute("width", column_info[j].p_width.asString())
1353                    << write_attribute("special", column_info[j].align_special)
1354                    << ">\n";
1355         }
1356         for (row_type i = 0; i < row_info.size(); ++i) {
1357                 static const string def("default");
1358                 os << "<row";
1359                 if (row_info[i].top_space_default)
1360                         os << write_attribute("topspace", def);
1361                 else
1362                         os << write_attribute("topspace", row_info[i].top_space);
1363                 if (row_info[i].bottom_space_default)
1364                         os << write_attribute("bottomspace", def);
1365                 else
1366                         os << write_attribute("bottomspace", row_info[i].bottom_space);
1367                 if (row_info[i].interline_space_default)
1368                         os << write_attribute("interlinespace", def);
1369                 else
1370                         os << write_attribute("interlinespace", row_info[i].interline_space);
1371                 os << write_attribute("endhead", row_info[i].endhead)
1372                    << write_attribute("endfirsthead", row_info[i].endfirsthead)
1373                    << write_attribute("endfoot", row_info[i].endfoot)
1374                    << write_attribute("endlastfoot", row_info[i].endlastfoot)
1375                    << write_attribute("newpage", row_info[i].newpage)
1376                    << write_attribute("caption", row_info[i].caption)
1377                    << ">\n";
1378                 for (col_type j = 0; j < column_info.size(); ++j) {
1379                         os << "<cell"
1380                            << write_attribute("multicolumn", cell_info[i][j].multicolumn)
1381                            << write_attribute("alignment", cell_info[i][j].alignment)
1382                            << write_attribute("valignment", cell_info[i][j].valignment)
1383                            << write_attribute("topline", cell_info[i][j].top_line)
1384                            << write_attribute("bottomline", cell_info[i][j].bottom_line)
1385                            << write_attribute("leftline", cell_info[i][j].left_line)
1386                            << write_attribute("rightline", cell_info[i][j].right_line)
1387                            << write_attribute("rotate", cell_info[i][j].rotate)
1388                            << write_attribute("usebox", cell_info[i][j].usebox)
1389                            << write_attribute("width", cell_info[i][j].p_width)
1390                            << write_attribute("special", cell_info[i][j].align_special)
1391                            << ">\n";
1392                         os << "\\begin_inset ";
1393                         cell_info[i][j].inset->write(os);
1394                         os << "\n\\end_inset\n"
1395                            << "</cell>\n";
1396                 }
1397                 os << "</row>\n";
1398         }
1399         os << "</lyxtabular>\n";
1400 }
1401
1402
1403 void Tabular::read(Lexer & lex)
1404 {
1405         string line;
1406         istream & is = lex.getStream();
1407
1408         l_getline(is, line);
1409         if (!prefixIs(line, "<lyxtabular ") && !prefixIs(line, "<Tabular ")) {
1410                 LASSERT(false, /**/);
1411                 return;
1412         }
1413
1414         int version;
1415         if (!getTokenValue(line, "version", version))
1416                 return;
1417         LASSERT(version >= 2, /**/);
1418
1419         int rows_arg;
1420         if (!getTokenValue(line, "rows", rows_arg))
1421                 return;
1422         int columns_arg;
1423         if (!getTokenValue(line, "columns", columns_arg))
1424                 return;
1425         init(buffer(), rows_arg, columns_arg);
1426         l_getline(is, line);
1427         if (!prefixIs(line, "<features")) {
1428                 lyxerr << "Wrong tabular format (expected <features ...> got"
1429                        << line << ')' << endl;
1430                 return;
1431         }
1432         getTokenValue(line, "rotate", rotate);
1433         getTokenValue(line, "booktabs", use_booktabs);
1434         getTokenValue(line, "islongtable", is_long_tabular);
1435         getTokenValue(line, "tabularvalignment", tabular_valignment);
1436         getTokenValue(line, "longtabularalignment", longtabular_alignment);
1437         getTokenValue(line, "firstHeadTopDL", endfirsthead.topDL);
1438         getTokenValue(line, "firstHeadBottomDL", endfirsthead.bottomDL);
1439         getTokenValue(line, "firstHeadEmpty", endfirsthead.empty);
1440         getTokenValue(line, "headTopDL", endhead.topDL);
1441         getTokenValue(line, "headBottomDL", endhead.bottomDL);
1442         getTokenValue(line, "footTopDL", endfoot.topDL);
1443         getTokenValue(line, "footBottomDL", endfoot.bottomDL);
1444         getTokenValue(line, "lastFootTopDL", endlastfoot.topDL);
1445         getTokenValue(line, "lastFootBottomDL", endlastfoot.bottomDL);
1446         getTokenValue(line, "lastFootEmpty", endlastfoot.empty);
1447
1448         for (col_type j = 0; j < column_info.size(); ++j) {
1449                 l_getline(is,line);
1450                 if (!prefixIs(line,"<column")) {
1451                         lyxerr << "Wrong tabular format (expected <column ...> got"
1452                                << line << ')' << endl;
1453                         return;
1454                 }
1455                 getTokenValue(line, "alignment", column_info[j].alignment);
1456                 getTokenValue(line, "valignment", column_info[j].valignment);
1457                 getTokenValue(line, "width", column_info[j].p_width);
1458                 getTokenValue(line, "special", column_info[j].align_special);
1459         }
1460
1461         for (row_type i = 0; i < row_info.size(); ++i) {
1462                 l_getline(is, line);
1463                 if (!prefixIs(line, "<row")) {
1464                         lyxerr << "Wrong tabular format (expected <row ...> got"
1465                                << line << ')' << endl;
1466                         return;
1467                 }
1468                 getTokenValue(line, "topspace", row_info[i].top_space,
1469                               row_info[i].top_space_default);
1470                 getTokenValue(line, "bottomspace", row_info[i].bottom_space,
1471                               row_info[i].bottom_space_default);
1472                 getTokenValue(line, "interlinespace", row_info[i].interline_space,
1473                               row_info[i].interline_space_default);
1474                 getTokenValue(line, "endfirsthead", row_info[i].endfirsthead);
1475                 getTokenValue(line, "endhead", row_info[i].endhead);
1476                 getTokenValue(line, "endfoot", row_info[i].endfoot);
1477                 getTokenValue(line, "endlastfoot", row_info[i].endlastfoot);
1478                 getTokenValue(line, "newpage", row_info[i].newpage);
1479                 getTokenValue(line, "caption", row_info[i].caption);
1480                 for (col_type j = 0; j < column_info.size(); ++j) {
1481                         l_getline(is, line);
1482                         if (!prefixIs(line, "<cell")) {
1483                                 lyxerr << "Wrong tabular format (expected <cell ...> got"
1484                                        << line << ')' << endl;
1485                                 return;
1486                         }
1487                         getTokenValue(line, "multicolumn", cell_info[i][j].multicolumn);
1488                         getTokenValue(line, "alignment", cell_info[i][j].alignment);
1489                         getTokenValue(line, "valignment", cell_info[i][j].valignment);
1490                         getTokenValue(line, "topline", cell_info[i][j].top_line);
1491                         getTokenValue(line, "bottomline", cell_info[i][j].bottom_line);
1492                         getTokenValue(line, "leftline", cell_info[i][j].left_line);
1493                         getTokenValue(line, "rightline", cell_info[i][j].right_line);
1494                         getTokenValue(line, "rotate", cell_info[i][j].rotate);
1495                         getTokenValue(line, "usebox", cell_info[i][j].usebox);
1496                         getTokenValue(line, "width", cell_info[i][j].p_width);
1497                         setFixedWidth(i,j);
1498                         getTokenValue(line, "special", cell_info[i][j].align_special);
1499                         l_getline(is, line);
1500                         if (prefixIs(line, "\\begin_inset")) {
1501                                 cell_info[i][j].inset->setBuffer(*buffer_);
1502                                 cell_info[i][j].inset->read(lex);
1503                                 l_getline(is, line);
1504                         }
1505                         if (!prefixIs(line, "</cell>")) {
1506                                 lyxerr << "Wrong tabular format (expected </cell> got"
1507                                        << line << ')' << endl;
1508                                 return;
1509                         }
1510                 }
1511                 l_getline(is, line);
1512                 if (!prefixIs(line, "</row>")) {
1513                         lyxerr << "Wrong tabular format (expected </row> got"
1514                                << line << ')' << endl;
1515                         return;
1516                 }
1517         }
1518         while (!prefixIs(line, "</lyxtabular>")) {
1519                 l_getline(is, line);
1520         }
1521         updateIndexes();
1522 }
1523
1524
1525 bool Tabular::isMultiColumn(idx_type cell) const
1526 {
1527         return cellInfo(cell).multicolumn != CELL_NORMAL;
1528 }
1529
1530
1531 bool Tabular::isMultiColumnReal(idx_type cell) const
1532 {
1533         return cellColumn(cell) != cellRightColumn(cell) &&
1534                         cellInfo(cell).multicolumn != CELL_NORMAL;
1535 }
1536
1537
1538 Tabular::CellData & Tabular::cellInfo(idx_type cell) const
1539 {
1540         return cell_info[cellRow(cell)][cellColumn(cell)];
1541 }
1542
1543
1544 void Tabular::setMultiColumn(idx_type cell, idx_type number)
1545 {
1546         CellData & cs = cellInfo(cell);
1547         cs.multicolumn = CELL_BEGIN_OF_MULTICOLUMN;
1548         cs.alignment = column_info[cellColumn(cell)].alignment;
1549         setRightLine(cell, rightLine(cell + number - 1));
1550         for (idx_type i = 1; i < number; ++i) {
1551                 CellData & cs1 = cellInfo(cell + i);
1552                 cs1.multicolumn = CELL_PART_OF_MULTICOLUMN;
1553                 cs.inset->appendParagraphs(cs1.inset->paragraphs());
1554                 cs1.inset->clear();
1555         }
1556         updateIndexes();
1557 }
1558
1559
1560 Tabular::idx_type Tabular::columnSpan(idx_type cell) const
1561 {
1562         row_type const row = cellRow(cell);
1563         col_type const ncols = column_info.size();
1564         idx_type result = 1;
1565         col_type column = cellColumn(cell) + 1;
1566         while (column < ncols && isPartOfMultiColumn(row, column)) {
1567                 ++result;
1568                 ++column;
1569         }
1570         return result;
1571 }
1572
1573
1574 Tabular::idx_type Tabular::unsetMultiColumn(idx_type cell)
1575 {
1576         row_type const row = cellRow(cell);
1577         col_type column = cellColumn(cell);
1578
1579         idx_type result = 0;
1580
1581         if (cell_info[row][column].multicolumn == CELL_BEGIN_OF_MULTICOLUMN) {
1582                 cell_info[row][column].multicolumn = CELL_NORMAL;
1583                 ++column;
1584                 while (column < column_info.size() &&
1585                            cell_info[row][column].multicolumn == CELL_PART_OF_MULTICOLUMN)
1586                 {
1587                         cell_info[row][column].multicolumn = CELL_NORMAL;
1588                         ++column;
1589                         ++result;
1590                 }
1591         }
1592         updateIndexes();
1593         return result;
1594 }
1595
1596
1597 void Tabular::setRotateCell(idx_type cell, bool flag)
1598 {
1599         cellInfo(cell).rotate = flag;
1600 }
1601
1602
1603 bool Tabular::getRotateCell(idx_type cell) const
1604 {
1605         return cellInfo(cell).rotate;
1606 }
1607
1608
1609 bool Tabular::needRotating() const
1610 {
1611         if (rotate)
1612                 return true;
1613         for (row_type i = 0; i < row_info.size(); ++i)
1614                 for (col_type j = 0; j < column_info.size(); ++j)
1615                         if (cell_info[i][j].rotate)
1616                                 return true;
1617         return false;
1618 }
1619
1620
1621 bool Tabular::isLastCell(idx_type cell) const
1622 {
1623         if (cell + 1 < numberofcells)
1624                 return false;
1625         return true;
1626 }
1627
1628
1629 Tabular::idx_type Tabular::cellAbove(idx_type cell) const
1630 {
1631         if (cellRow(cell) > 0)
1632                 return cell_info[cellRow(cell)-1][cellColumn(cell)].cellno;
1633         return cell;
1634 }
1635
1636
1637 Tabular::idx_type Tabular::cellBelow(idx_type cell) const
1638 {
1639         if (cellRow(cell) + 1 < row_info.size())
1640                 return cell_info[cellRow(cell)+1][cellColumn(cell)].cellno;
1641         return cell;
1642 }
1643
1644
1645 Tabular::idx_type Tabular::cellIndex(row_type row,
1646                                                col_type column) const
1647 {
1648         BOOST_ASSERT(column != npos && column < column_info.size()
1649                 && row != npos && row < row_info.size());
1650         return cell_info[row][column].cellno;
1651 }
1652
1653
1654 void Tabular::setUsebox(idx_type cell, BoxType type)
1655 {
1656         cellInfo(cell).usebox = type;
1657 }
1658
1659
1660 // FIXME: Remove this routine because we cannot insert \parboxes when the user
1661 // adds line breaks, see bug 4886.
1662 Tabular::BoxType Tabular::getUsebox(idx_type cell) const
1663 {
1664         if ((!column_info[cellColumn(cell)].p_width.zero() && !isMultiColumn(cell)) ||
1665                 (isMultiColumn(cell) && !cellInfo(cell).p_width.zero()))
1666                 return BOX_NONE;
1667         if (cellInfo(cell).usebox > 1)
1668                 return cellInfo(cell).usebox;
1669         return useParbox(cell);
1670 }
1671
1672
1673 ///
1674 //  This are functions used for the longtable support
1675 ///
1676 void Tabular::setLTHead(row_type row, bool flag, ltType const & hd,
1677                            bool first)
1678 {
1679         if (first) {
1680                 endfirsthead = hd;
1681                 if (hd.set)
1682                         row_info[row].endfirsthead = flag;
1683         } else {
1684                 endhead = hd;
1685                 if (hd.set)
1686                         row_info[row].endhead = flag;
1687         }
1688 }
1689
1690
1691 bool Tabular::getRowOfLTHead(row_type row, ltType & hd) const
1692 {
1693         hd = endhead;
1694         hd.set = haveLTHead();
1695         return row_info[row].endhead;
1696 }
1697
1698
1699 bool Tabular::getRowOfLTFirstHead(row_type row, ltType & hd) const
1700 {
1701         hd = endfirsthead;
1702         hd.set = haveLTFirstHead();
1703         return row_info[row].endfirsthead;
1704 }
1705
1706
1707 void Tabular::setLTFoot(row_type row, bool flag, ltType const & fd,
1708                            bool last)
1709 {
1710         if (last) {
1711                 endlastfoot = fd;
1712                 if (fd.set)
1713                         row_info[row].endlastfoot = flag;
1714         } else {
1715                 endfoot = fd;
1716                 if (fd.set)
1717                         row_info[row].endfoot = flag;
1718         }
1719 }
1720
1721
1722 bool Tabular::getRowOfLTFoot(row_type row, ltType & fd) const
1723 {
1724         fd = endfoot;
1725         fd.set = haveLTFoot();
1726         return row_info[row].endfoot;
1727 }
1728
1729
1730 bool Tabular::getRowOfLTLastFoot(row_type row, ltType & fd) const
1731 {
1732         fd = endlastfoot;
1733         fd.set = haveLTLastFoot();
1734         return row_info[row].endlastfoot;
1735 }
1736
1737
1738 void Tabular::setLTNewPage(row_type row, bool what)
1739 {
1740         row_info[row].newpage = what;
1741 }
1742
1743
1744 bool Tabular::getLTNewPage(row_type row) const
1745 {
1746         return row_info[row].newpage;
1747 }
1748
1749
1750 bool Tabular::haveLTHead() const
1751 {
1752         for (row_type i = 0; i < row_info.size(); ++i)
1753                 if (row_info[i].endhead)
1754                         return true;
1755         return false;
1756 }
1757
1758
1759 bool Tabular::haveLTFirstHead() const
1760 {
1761         if (endfirsthead.empty)
1762                 return false;
1763         for (row_type i = 0; i < row_info.size(); ++i)
1764                 if (row_info[i].endfirsthead)
1765                         return true;
1766         return false;
1767 }
1768
1769
1770 bool Tabular::haveLTFoot() const
1771 {
1772         for (row_type i = 0; i < row_info.size(); ++i)
1773                 if (row_info[i].endfoot)
1774                         return true;
1775         return false;
1776 }
1777
1778
1779 bool Tabular::haveLTLastFoot() const
1780 {
1781         if (endlastfoot.empty)
1782                 return false;
1783         for (row_type i = 0; i < row_info.size(); ++i)
1784                 if (row_info[i].endlastfoot)
1785                         return true;
1786         return false;
1787 }
1788
1789
1790 Tabular::idx_type Tabular::setLTCaption(row_type row, bool what)
1791 {
1792         idx_type i = getFirstCellInRow(row);
1793         if (what) {
1794                 setMultiColumn(i, numberOfCellsInRow(i));
1795                 setTopLine(i, false);
1796                 setBottomLine(i, false);
1797                 setLeftLine(i, false);
1798                 setRightLine(i, false);
1799         } else {
1800                 unsetMultiColumn(i);
1801                 // FIXME: when unsetting a caption row, also all existing captions
1802                 // in this row must be dissolved, see (bug 5754)
1803                 // dispatch(FuncRequest(LFUN_INSET_DISSOLVE, "caption-insert"));
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 bool Tabular::plaintextTopHLine(odocstream & os, row_type row,
2637                                    vector<unsigned int> const & clen) const
2638 {
2639         idx_type const fcell = getFirstCellInRow(row);
2640         idx_type const n = numberOfCellsInRow(fcell) + fcell;
2641         idx_type tmp = 0;
2642
2643         for (idx_type i = fcell; i < n; ++i) {
2644                 if (topLine(i)) {
2645                         ++tmp;
2646                         break;
2647                 }
2648         }
2649         if (!tmp)
2650                 return false;
2651
2652         char_type ch;
2653         for (idx_type i = fcell; i < n; ++i) {
2654                 if (topLine(i)) {
2655                         if (leftLine(i))
2656                                 os << "+-";
2657                         else
2658                                 os << "--";
2659                         ch = '-';
2660                 } else {
2661                         os << "  ";
2662                         ch = ' ';
2663                 }
2664                 col_type column = cellColumn(i);
2665                 int len = clen[column];
2666                 while (column < column_info.size() - 1
2667                        && isPartOfMultiColumn(row, ++column))
2668                         len += clen[column] + 4;
2669                 os << docstring(len, ch);
2670                 if (topLine(i)) {
2671                         if (rightLine(i))
2672                                 os << "-+";
2673                         else
2674                                 os << "--";
2675                 } else {
2676                         os << "  ";
2677                 }
2678         }
2679         os << endl;
2680         return true;
2681 }
2682
2683
2684 bool Tabular::plaintextBottomHLine(odocstream & os, row_type row,
2685                                       vector<unsigned int> const & clen) const
2686 {
2687         idx_type const fcell = getFirstCellInRow(row);
2688         idx_type const n = numberOfCellsInRow(fcell) + fcell;
2689         idx_type tmp = 0;
2690
2691         for (idx_type i = fcell; i < n; ++i) {
2692                 if (bottomLine(i)) {
2693                         ++tmp;
2694                         break;
2695                 }
2696         }
2697         if (!tmp)
2698                 return false;
2699
2700         char_type ch;
2701         for (idx_type i = fcell; i < n; ++i) {
2702                 if (bottomLine(i)) {
2703                         if (leftLine(i))
2704                                 os << "+-";
2705                         else
2706                                 os << "--";
2707                         ch = '-';
2708                 } else {
2709                         os << "  ";
2710                         ch = ' ';
2711                 }
2712                 col_type column = cellColumn(i);
2713                 int len = clen[column];
2714                 while (column < column_info.size() -1
2715                        && isPartOfMultiColumn(row, ++column))
2716                         len += clen[column] + 4;
2717                 os << docstring(len, ch);
2718                 if (bottomLine(i)) {
2719                         if (rightLine(i))
2720                                 os << "-+";
2721                         else
2722                                 os << "--";
2723                 } else {
2724                         os << "  ";
2725                 }
2726         }
2727         os << endl;
2728         return true;
2729 }
2730
2731
2732 void Tabular::plaintextPrintCell(odocstream & os,
2733                                OutputParams const & runparams,
2734                                idx_type cell, row_type row, col_type column,
2735                                vector<unsigned int> const & clen,
2736                                bool onlydata) const
2737 {
2738         odocstringstream sstr;
2739         cellInset(cell)->plaintext(sstr, runparams);
2740
2741         if (onlydata) {
2742                 os << sstr.str();
2743                 return;
2744         }
2745
2746         if (leftLine(cell))
2747                 os << "| ";
2748         else
2749                 os << "  ";
2750
2751         unsigned int len1 = sstr.str().length();
2752         unsigned int len2 = clen[column];
2753         while (column < column_info.size() -1
2754                && isPartOfMultiColumn(row, ++column))
2755                 len2 += clen[column] + 4;
2756         len2 -= len1;
2757
2758         switch (getAlignment(cell)) {
2759         default:
2760         case LYX_ALIGN_LEFT:
2761                 len1 = 0;
2762                 break;
2763         case LYX_ALIGN_RIGHT:
2764                 len1 = len2;
2765                 len2 = 0;
2766                 break;
2767         case LYX_ALIGN_CENTER:
2768                 len1 = len2 / 2;
2769                 len2 -= len1;
2770                 break;
2771         }
2772
2773         os << docstring(len1, ' ') << sstr.str()
2774            << docstring(len2, ' ');
2775
2776         if (rightLine(cell))
2777                 os << " |";
2778         else
2779                 os << "  ";
2780 }
2781
2782
2783 void Tabular::plaintext(odocstream & os,
2784                            OutputParams const & runparams, int const depth,
2785                            bool onlydata, char_type delim) const
2786 {
2787         // first calculate the width of the single columns
2788         vector<unsigned int> clen(column_info.size());
2789
2790         if (!onlydata) {
2791                 // first all non (real) multicolumn cells!
2792                 for (col_type j = 0; j < column_info.size(); ++j) {
2793                         clen[j] = 0;
2794                         for (row_type i = 0; i < row_info.size(); ++i) {
2795                                 idx_type cell = cellIndex(i, j);
2796                                 if (isMultiColumnReal(cell))
2797                                         continue;
2798                                 odocstringstream sstr;
2799                                 cellInset(cell)->plaintext(sstr, runparams);
2800                                 if (clen[j] < sstr.str().length())
2801                                         clen[j] = sstr.str().length();
2802                         }
2803                 }
2804                 // then all (real) multicolumn cells!
2805                 for (col_type j = 0; j < column_info.size(); ++j) {
2806                         for (row_type i = 0; i < row_info.size(); ++i) {
2807                                 idx_type cell = cellIndex(i, j);
2808                                 if (!isMultiColumnReal(cell) || isPartOfMultiColumn(i, j))
2809                                         continue;
2810                                 odocstringstream sstr;
2811                                 cellInset(cell)->plaintext(sstr, runparams);
2812                                 int len = int(sstr.str().length());
2813                                 idx_type const n = columnSpan(cell);
2814                                 for (col_type k = j; len > 0 && k < j + n - 1; ++k)
2815                                         len -= clen[k];
2816                                 if (len > int(clen[j + n - 1]))
2817                                         clen[j + n - 1] = len;
2818                         }
2819                 }
2820         }
2821         idx_type cell = 0;
2822         for (row_type i = 0; i < row_info.size(); ++i) {
2823                 if (!onlydata && plaintextTopHLine(os, i, clen))
2824                         os << docstring(depth * 2, ' ');
2825                 for (col_type j = 0; j < column_info.size(); ++j) {
2826                         if (isPartOfMultiColumn(i, j))
2827                                 continue;
2828                         if (onlydata && j > 0)
2829                                 // we don't use operator<< for single UCS4 character.
2830                                 // see explanation in docstream.h
2831                                 os.put(delim);
2832                         plaintextPrintCell(os, runparams, cell, i, j, clen, onlydata);
2833                         ++cell;
2834                 }
2835                 os << endl;
2836                 if (!onlydata) {
2837                         os << docstring(depth * 2, ' ');
2838                         if (plaintextBottomHLine(os, i, clen))
2839                                 os << docstring(depth * 2, ' ');
2840                 }
2841         }
2842 }
2843
2844
2845 shared_ptr<InsetTableCell> Tabular::cellInset(idx_type cell) const
2846 {
2847         return cell_info[cellRow(cell)][cellColumn(cell)].inset;
2848 }
2849
2850
2851 shared_ptr<InsetTableCell> Tabular::cellInset(row_type row,
2852                                                col_type column) const
2853 {
2854         return cell_info[row][column].inset;
2855 }
2856
2857
2858 void Tabular::setCellInset(row_type row, col_type column,
2859                               shared_ptr<InsetTableCell> ins) const
2860 {
2861         CellData & cd = cell_info[row][column];
2862         cd.inset = ins;
2863 }
2864
2865
2866 void Tabular::validate(LaTeXFeatures & features) const
2867 {
2868         features.require("NeedTabularnewline");
2869         if (use_booktabs)
2870                 features.require("booktabs");
2871         if (is_long_tabular)
2872                 features.require("longtable");
2873         if (needRotating())
2874                 features.require("rotating");
2875         for (idx_type cell = 0; cell < numberofcells; ++cell) {
2876                 if (getVAlignment(cell) != LYX_VALIGN_TOP
2877                     || !getPWidth(cell).zero())
2878                         features.require("array");
2879                 cellInset(cell)->validate(features);
2880         }
2881 }
2882
2883
2884 Tabular::BoxType Tabular::useParbox(idx_type cell) const
2885 {
2886         ParagraphList const & parlist = cellInset(cell)->paragraphs();
2887         ParagraphList::const_iterator cit = parlist.begin();
2888         ParagraphList::const_iterator end = parlist.end();
2889
2890         for (; cit != end; ++cit)
2891                 for (int i = 0; i < cit->size(); ++i)
2892                         if (cit->isNewline(i))
2893                                 return BOX_PARBOX;
2894
2895         return BOX_NONE;
2896 }
2897
2898
2899 /////////////////////////////////////////////////////////////////////
2900 //
2901 // InsetTableCell
2902 //
2903 /////////////////////////////////////////////////////////////////////
2904
2905 InsetTableCell::InsetTableCell(Buffer & buf)
2906         : InsetText(buf, InsetText::PlainLayout), isFixedWidth(false),
2907           contentAlign(LYX_ALIGN_CENTER)
2908 {}
2909
2910
2911 bool InsetTableCell::forcePlainLayout(idx_type) const
2912 {
2913         return !isFixedWidth;
2914 }
2915
2916
2917 bool InsetTableCell::allowParagraphCustomization(idx_type) const
2918 {
2919         return isFixedWidth;
2920 }
2921
2922
2923 bool InsetTableCell::getStatus(Cursor & cur, FuncRequest const & cmd,
2924         FuncStatus & status) const
2925 {
2926         bool enabled;
2927         switch (cmd.action) {
2928         case LFUN_LAYOUT:
2929                 enabled = !forcePlainLayout();
2930                 break;
2931         case LFUN_LAYOUT_PARAGRAPH:
2932                 enabled = allowParagraphCustomization();
2933                 break;
2934         default:
2935                 return InsetText::getStatus(cur, cmd, status);
2936         }
2937         status.setEnabled(enabled);
2938         return true;
2939 }
2940
2941 docstring InsetTableCell::asString(bool intoInsets) 
2942 {
2943         docstring retval;
2944         if (paragraphs().empty())
2945                 return retval;
2946         ParagraphList::const_iterator it = paragraphs().begin();
2947         ParagraphList::const_iterator en = paragraphs().end();
2948         bool first = true;
2949         for (; it != en; ++it) {
2950                 if (!first)
2951                         retval += "\n";
2952                 else
2953                         first = false;
2954                 retval += it->asString(intoInsets ? AS_STR_INSETS : AS_STR_NONE);
2955         }
2956         return retval;
2957 }
2958
2959
2960
2961 /////////////////////////////////////////////////////////////////////
2962 //
2963 // InsetTabular
2964 //
2965 /////////////////////////////////////////////////////////////////////
2966
2967 InsetTabular::InsetTabular(Buffer & buf, row_type rows,
2968                            col_type columns)
2969         : tabular(buf, max(rows, row_type(1)), max(columns, col_type(1))), scx_(0), 
2970         rowselect_(false), colselect_(false)
2971 {
2972         setBuffer(buf); // FIXME: remove later
2973 }
2974
2975
2976 InsetTabular::InsetTabular(InsetTabular const & tab)
2977         : Inset(tab), tabular(tab.tabular),  scx_(0)
2978 {
2979 }
2980
2981
2982 InsetTabular::~InsetTabular()
2983 {
2984         hideDialogs("tabular", this);
2985 }
2986
2987
2988 void InsetTabular::setBuffer(Buffer & buf)
2989 {
2990         tabular.setBuffer(buf);
2991         Inset::setBuffer(buf);
2992 }
2993
2994
2995 bool InsetTabular::insetAllowed(InsetCode code) const
2996 {
2997         if (code == MATHMACRO_CODE
2998                 || (code == CAPTION_CODE && !tabular.is_long_tabular))
2999                 return false;
3000
3001         return true;
3002 }
3003
3004
3005 void InsetTabular::write(ostream & os) const
3006 {
3007         os << "Tabular" << endl;
3008         tabular.write(os);
3009 }
3010
3011
3012 docstring InsetTabular::contextMenu(BufferView const &, int, int) const
3013 {
3014         // FIXME: depending on the selection state, we could offer a different menu.
3015         return from_ascii("context-tabular");
3016 }
3017
3018
3019 void InsetTabular::read(Lexer & lex)
3020 {
3021         //bool const old_format = (lex.getString() == "\\LyXTable");
3022
3023         tabular.read(lex);
3024
3025         //if (old_format)
3026         //      return;
3027
3028         lex.next();
3029         string token = lex.getString();
3030         while (lex && token != "\\end_inset") {
3031                 lex.next();
3032                 token = lex.getString();
3033         }
3034         if (!lex)
3035                 lex.printError("Missing \\end_inset at this point. ");
3036 }
3037
3038
3039 int InsetTabular::rowFromY(Cursor & cur, int y) const
3040 {
3041         // top y coordinate of tabular
3042         int h = yo(cur.bv()) - tabular.rowAscent(0);
3043         size_t nrows = tabular.row_info.size();
3044         row_type r = 0;
3045         for (; r < nrows && y > h; ++r) {
3046                 h += tabular.rowAscent(r);
3047                 h += tabular.rowDescent(r);
3048                 h += tabular.getAdditionalHeight(r);
3049         }
3050         return r - 1;
3051 }
3052
3053
3054 int InsetTabular::columnFromX(Cursor & cur, int x) const
3055 {
3056         // left x coordinate of tabular
3057         int w = xo(cur.bv()) + ADD_TO_TABULAR_WIDTH;
3058         size_t ncols = tabular.column_info.size();
3059         col_type c = 0;
3060         for (; c < ncols && x > w; ++c)
3061                 w += tabular.columnWidth(c);
3062         return c - 1;
3063 }
3064
3065
3066 void InsetTabular::metrics(MetricsInfo & mi, Dimension & dim) const
3067 {
3068         //lyxerr << "InsetTabular::metrics: " << mi.base.bv << " width: " <<
3069         //      mi.base.textwidth << "\n";
3070         if (!mi.base.bv) {
3071                 LYXERR0("need bv");
3072                 LASSERT(false, /**/);
3073         }
3074
3075         row_type i = 0;
3076         for (idx_type cell = 0; i < tabular.row_info.size(); ++i) {
3077                 int maxAsc = 0;
3078                 int maxDesc = 0;
3079                 for (col_type j = 0; j < tabular.column_info.size(); ++j) {
3080                         if (tabular.isPartOfMultiColumn(i, j))
3081                                 // Multicolumn cell, but not first one
3082                                 continue;
3083                         Dimension dim;
3084                         MetricsInfo m = mi;
3085                         Length p_width;
3086                         if (tabular.cell_info[i][j].multicolumn ==
3087                                 Tabular::CELL_BEGIN_OF_MULTICOLUMN)
3088                                 p_width = tabular.cellInfo(cell).p_width;
3089                         else
3090                                 p_width = tabular.column_info[j].p_width;
3091                         if (!p_width.zero())
3092                                 m.base.textwidth = p_width.inPixels(mi.base.textwidth);
3093                         tabular.cellInset(cell)->metrics(m, dim);
3094                         if (!p_width.zero())
3095                                 dim.wid = m.base.textwidth;
3096                         tabular.setCellWidth(cell, dim.wid);
3097                         maxAsc  = max(maxAsc, dim.asc);
3098                         maxDesc = max(maxDesc, dim.des);
3099                         ++cell;
3100                 }
3101                 int const top_space = tabular.row_info[i].top_space_default ?
3102                         default_line_space :
3103                         tabular.row_info[i].top_space.inPixels(mi.base.textwidth);
3104                 tabular.setRowAscent(i, maxAsc + ADD_TO_HEIGHT + top_space);
3105                 int const bottom_space = tabular.row_info[i].bottom_space_default ?
3106                         default_line_space :
3107                         tabular.row_info[i].bottom_space.inPixels(mi.base.textwidth);
3108                 tabular.setRowDescent(i, maxDesc + ADD_TO_HEIGHT + bottom_space);
3109         }
3110         tabular.updateColumnWidths();
3111         dim.asc = tabular.rowAscent(0);
3112         dim.des = tabular.height() - dim.asc;
3113         dim.wid = tabular.width() + 2 * ADD_TO_TABULAR_WIDTH;
3114 }
3115
3116 bool InsetTabular::isCellSelected(Cursor & cur, row_type row, col_type col) 
3117         const
3118 {
3119         if (&cur.inset() == this && cur.selection()) {
3120                 if (cur.selIsMultiCell()) {
3121                         row_type rs, re;
3122                         col_type cs, ce;
3123                         getSelection(cur, rs, re, cs, ce);
3124                         
3125                         if (col >= cs && col <= ce && row >= rs && row <= re)
3126                                 return true;
3127                 } else 
3128                         if (col == tabular.cellColumn(cur.idx()) 
3129                                 && row == tabular.cellRow(cur.idx())) {
3130                         CursorSlice const & beg = cur.selBegin();
3131                         CursorSlice const & end = cur.selEnd();
3132
3133                         if ((end.lastpos() > 0 || end.lastpit() > 0)
3134                                   && end.pos() == end.lastpos() && beg.pos() == 0
3135                                   && end.pit() == end.lastpit() && beg.pit() == 0)
3136                                 return true;
3137                 }
3138         }
3139         return false;
3140 }
3141
3142
3143 void InsetTabular::draw(PainterInfo & pi, int x, int y) const
3144 {
3145         //lyxerr << "InsetTabular::draw: " << x << " " << y << endl;
3146         BufferView * bv = pi.base.bv;
3147         Cursor & cur = pi.base.bv->cursor();
3148
3149         // FIXME: As the full background is painted in drawSelection(),
3150         // we have no choice but to do a full repaint for the Text cells.
3151         pi.full_repaint = true;
3152
3153         resetPos(bv->cursor());
3154
3155         x += scx_;
3156         x += ADD_TO_TABULAR_WIDTH;
3157
3158         bool const original_drawing_state = pi.pain.isDrawingEnabled();
3159         bool const original_selection_state = pi.selected;
3160
3161         idx_type idx = 0;
3162         first_visible_cell = Tabular::npos;
3163         for (row_type i = 0; i < tabular.row_info.size(); ++i) {
3164                 int nx = x;
3165                 int const a = tabular.rowAscent(i);
3166                 int const d = tabular.rowDescent(i);
3167                 idx = tabular.cellIndex(i, 0);
3168                 for (col_type j = 0; j < tabular.column_info.size(); ++j) {
3169                         if (tabular.isPartOfMultiColumn(i, j))
3170                                 continue;
3171                         if (first_visible_cell == Tabular::npos)
3172                                 first_visible_cell = idx;
3173
3174                         pi.selected |= isCellSelected(cur, i, j);
3175                         int const cx = nx + tabular.getBeginningOfTextInCell(idx);
3176                         // Cache the Inset position.
3177                         bv->coordCache().insets().add(cell(idx).get(), cx, y);
3178                         if (nx + tabular.columnWidth(idx) < 0
3179                             || nx > bv->workWidth()
3180                             || y + d < 0
3181                             || y - a > bv->workHeight()) {
3182                                 pi.pain.setDrawingEnabled(false);
3183                                 cell(idx)->draw(pi, cx, y);
3184                                 drawCellLines(pi.pain, nx, y, i, idx, pi.change_);
3185                                 pi.pain.setDrawingEnabled(original_drawing_state);
3186                         } else {
3187                                 cell(idx)->draw(pi, cx, y);
3188                                 drawCellLines(pi.pain, nx, y, i, idx, pi.change_);
3189                         }
3190                         nx += tabular.columnWidth(idx);
3191                         ++idx;
3192                         pi.selected = original_selection_state;
3193                 }
3194
3195                 if (i + 1 < tabular.row_info.size())
3196                         y += d + tabular.rowAscent(i + 1) +
3197                                 tabular.getAdditionalHeight(i + 1);
3198         }
3199 }
3200
3201
3202 void InsetTabular::drawSelection(PainterInfo & pi, int x, int y) const
3203 {
3204         Cursor & cur = pi.base.bv->cursor();
3205         resetPos(cur);
3206
3207         x += scx_ + ADD_TO_TABULAR_WIDTH;
3208
3209         // FIXME: it is wrong to completely paint the background
3210         // if we want to do single row painting.
3211
3212         // Paint background of current tabular
3213         int const w = tabular.width();
3214         int const h = tabular.height();
3215         int yy = y - tabular.rowAscent(0);
3216         pi.pain.fillRectangle(x, yy, w, h, pi.backgroundColor(this));
3217
3218         if (!cur.selection())
3219                 return;
3220         if (&cur.inset() != this)
3221                 return;
3222
3223         //resetPos(cur);
3224
3225         bool const full_cell_selected = isCellSelected(cur,
3226                 tabular.cellRow(cur.idx()), tabular.cellColumn(cur.idx()));
3227
3228         if (cur.selIsMultiCell() || full_cell_selected) {
3229                 y -= tabular.rowAscent(0);
3230                 for (row_type j = 0; j < tabular.row_info.size(); ++j) {
3231                         int const a = tabular.rowAscent(j);
3232                         int const h = a + tabular.rowDescent(j);
3233                         int xx = x;
3234                         y += tabular.getAdditionalHeight(j);
3235                         for (col_type i = 0; i < tabular.column_info.size(); ++i) {
3236                                 if (tabular.isPartOfMultiColumn(j, i))
3237                                         continue;
3238                                 idx_type const cell =
3239                                         tabular.cellIndex(j, i);
3240                                 int const w = tabular.columnWidth(cell);
3241                                 if (isCellSelected(cur, j, i))
3242                                         pi.pain.fillRectangle(xx, y, w, h, Color_selection);
3243                                 xx += w;
3244                         }
3245                         y += h;
3246                 }
3247
3248         } else {
3249                 x += cellXPos(cur.idx());
3250                 x += tabular.getBeginningOfTextInCell(cur.idx());
3251                 cell(cur.idx())->drawSelection(pi, x, 0 /* ignored */);
3252         }
3253 }
3254
3255
3256 void InsetTabular::drawCellLines(Painter & pain, int x, int y,
3257                                  row_type row, idx_type cell, Change const & change) const
3258 {
3259         int x2 = x + tabular.columnWidth(cell);
3260         bool on_off = false;
3261         Color col = Color_tabularline;
3262         Color onoffcol = Color_tabularonoffline;
3263
3264         if (change.changed()) {
3265                 col = change.color();
3266                 onoffcol = change.color();
3267         }
3268
3269         if (!tabular.topAlreadyDrawn(cell)) {
3270                 on_off = !tabular.topLine(cell);
3271                 pain.line(x, y - tabular.rowAscent(row),
3272                           x2, y -  tabular.rowAscent(row),
3273                           on_off ? onoffcol : col,
3274                           on_off ? Painter::line_onoffdash : Painter::line_solid);
3275         }
3276         on_off = !tabular.bottomLine(cell);
3277         pain.line(x, y + tabular.rowDescent(row),
3278                   x2, y + tabular.rowDescent(row),
3279                   on_off ? onoffcol : col,
3280                   on_off ? Painter::line_onoffdash : Painter::line_solid);
3281         if (!tabular.leftAlreadyDrawn(cell)) {
3282                 on_off = !tabular.leftLine(cell);
3283                 pain.line(x, y -  tabular.rowAscent(row),
3284                           x, y +  tabular.rowDescent(row),
3285                           on_off ? onoffcol : col,
3286                           on_off ? Painter::line_onoffdash : Painter::line_solid);
3287         }
3288         on_off = !tabular.rightLine(cell);
3289         pain.line(x2 - tabular.getAdditionalWidth(cell),
3290                   y -  tabular.rowAscent(row),
3291                   x2 - tabular.getAdditionalWidth(cell),
3292                   y +  tabular.rowDescent(row),
3293                   on_off ? onoffcol : col,
3294                   on_off ? Painter::line_onoffdash : Painter::line_solid);
3295 }
3296
3297
3298 docstring InsetTabular::editMessage() const
3299 {
3300         return _("Opened table");
3301 }
3302
3303
3304 void InsetTabular::edit(Cursor & cur, bool front, EntryDirection)
3305 {
3306         //lyxerr << "InsetTabular::edit: " << this << endl;
3307         cur.finishUndo();
3308         cur.setSelection(false);
3309         cur.push(*this);
3310         if (front) {
3311                 if (isRightToLeft(cur))
3312                         cur.idx() = tabular.getLastCellInRow(0);
3313                 else
3314                         cur.idx() = 0;
3315                 cur.pit() = 0;
3316                 cur.pos() = 0;
3317         } else {
3318                 if (isRightToLeft(cur))
3319                         cur.idx() = tabular.getFirstCellInRow(tabular.row_info.size() - 1);
3320                 else
3321                         cur.idx() = tabular.numberofcells - 1;
3322                 cur.pit() = 0;
3323                 cur.pos() = cur.lastpos(); // FIXME crude guess
3324         }
3325         // FIXME: this accesses the position cache before it is initialized
3326         //resetPos(cur);
3327         //cur.bv().fitCursor();
3328 }
3329
3330
3331 void InsetTabular::updateLabels(ParIterator const & it)
3332 {
3333         // In a longtable, tell captions what the current float is
3334         Counters & cnts = buffer().masterBuffer()->params().documentClass().counters();
3335         string const saveflt = cnts.current_float();
3336         if (tabular.is_long_tabular)
3337                 cnts.current_float("table");
3338
3339         ParIterator it2 = it;
3340         it2.forwardPos();
3341         size_t const end = it2.nargs();
3342         for ( ; it2.idx() < end; it2.top().forwardIdx())
3343                 buffer().updateLabels(it2);
3344
3345         //reset afterwards
3346         if (tabular.is_long_tabular)
3347                 cnts.current_float(saveflt);
3348 }
3349
3350
3351 void InsetTabular::doDispatch(Cursor & cur, FuncRequest & cmd)
3352 {
3353         LYXERR(Debug::DEBUG, "# InsetTabular::doDispatch: cmd: " << cmd
3354                              << "\n  cur:" << cur);
3355         CursorSlice sl = cur.top();
3356         Cursor & bvcur = cur.bv().cursor();
3357
3358         switch (cmd.action) {
3359
3360         case LFUN_MOUSE_PRESS: {
3361                 //lyxerr << "# InsetTabular::MousePress\n" << cur.bv().cursor() << endl;
3362                 // select row
3363                 if (cmd.x < xo(cur.bv()) + ADD_TO_TABULAR_WIDTH
3364                         || cmd.x > xo(cur.bv()) + tabular.width()) {
3365                         row_type r = rowFromY(cur, cmd.y);
3366                         cur.idx() = tabular.getFirstCellInRow(r);
3367                         cur.pos() = 0;
3368                         cur.resetAnchor();
3369                         cur.idx() = tabular.getLastCellInRow(r);
3370                         cur.pos() = cur.lastpos();
3371                         cur.setSelection(true);
3372                         bvcur = cur; 
3373                         rowselect_ = true;
3374                         break;
3375                 }
3376                 // select column
3377                 int const y0 = yo(cur.bv()) - tabular.rowAscent(0);
3378                 if (cmd.y < y0 + ADD_TO_TABULAR_WIDTH 
3379                         || cmd.y > y0 + tabular.height()) {
3380                         col_type c = columnFromX(cur, cmd.x);
3381                         cur.idx() = tabular.cellIndex(0, c);
3382                         cur.pos() = 0;
3383                         cur.resetAnchor();
3384                         cur.idx() = tabular.cellIndex(tabular.row_info.size() - 1, c);
3385                         cur.pos() = cur.lastpos();
3386                         cur.setSelection(true);
3387                         bvcur = cur; 
3388                         colselect_ = true;
3389                         break;
3390                 }
3391                 // do not reset cursor/selection if we have selected
3392                 // some cells (bug 2715).
3393                 if (cmd.button() == mouse_button::button3
3394                     && &bvcur.selBegin().inset() == this 
3395                     && bvcur.selIsMultiCell()) 
3396                         ;
3397                 else
3398                         // Let InsetTableCell do it
3399                         cell(cur.idx())->dispatch(cur, cmd);
3400                 break;
3401         }
3402         case LFUN_MOUSE_MOTION:
3403                 //lyxerr << "# InsetTabular::MouseMotion\n" << bvcur << endl;
3404                 if (cmd.button() == mouse_button::button1) {
3405                         // only accept motions to places not deeper nested than the real anchor
3406                         if (!bvcur.anchor_.hasPart(cur)) {
3407                                 cur.undispatched();
3408                                 break;
3409                         }
3410                         // select (additional) row
3411                         if (rowselect_) {
3412                                 row_type r = rowFromY(cur, cmd.y);
3413                                 cur.idx() = tabular.getLastCellInRow(r);
3414                                 // we need to reset the cursor's pit and pos now, as the old ones
3415                                 // may no longer be valid.
3416                                 cur.pit() = 0;
3417                                 cur.pos() = 0;
3418                                 bvcur.setCursor(cur);
3419                                 bvcur.setSelection(true);
3420                                 break;
3421                         }
3422                         // select (additional) column
3423                         if (colselect_) {
3424                                 col_type c = columnFromX(cur, cmd.x);
3425                                 cur.idx() = tabular.cellIndex(tabular.row_info.size() - 1, c);
3426                                 // we need to reset the cursor's pit and pos now, as the old ones
3427                                 // may no longer be valid.
3428                                 cur.pit() = 0;
3429                                 cur.pos() = 0;
3430                                 bvcur.setCursor(cur);
3431                                 bvcur.setSelection(true);
3432                                 break;
3433                         }
3434                         // only update if selection changes
3435                         if (bvcur.idx() == cur.idx() &&
3436                                 !(bvcur.anchor_.idx() == cur.idx() && bvcur.pos() != cur.pos()))
3437                                 cur.noUpdate();
3438                         setCursorFromCoordinates(cur, cmd.x, cmd.y);
3439                         bvcur.setCursor(cur);
3440                         bvcur.setSelection(true);
3441                         // if this is a multicell selection, we just set the cursor to
3442                         // the beginning of the cell's text.
3443                         if (bvcur.selIsMultiCell()) {
3444                                 bvcur.pit() = bvcur.lastpit();
3445                                 bvcur.pos() = bvcur.lastpos();
3446                         }
3447                 }
3448                 break;
3449
3450         case LFUN_MOUSE_RELEASE:
3451                 rowselect_ = false;
3452                 colselect_ = false;
3453                 break;
3454
3455         case LFUN_CELL_BACKWARD:
3456                 movePrevCell(cur);
3457                 cur.setSelection(false);
3458                 break;
3459
3460         case LFUN_CELL_FORWARD:
3461                 moveNextCell(cur);
3462                 cur.setSelection(false);
3463                 break;
3464
3465         case LFUN_CHAR_FORWARD_SELECT:
3466         case LFUN_CHAR_FORWARD:
3467         case LFUN_CHAR_BACKWARD_SELECT:
3468         case LFUN_CHAR_BACKWARD:
3469         case LFUN_CHAR_RIGHT_SELECT:
3470         case LFUN_CHAR_RIGHT:
3471         case LFUN_CHAR_LEFT_SELECT:
3472         case LFUN_CHAR_LEFT: {
3473                 // determine whether we move to next or previous cell, where to enter 
3474                 // the new cell from, and which command to "finish" (i.e., exit the
3475                 // inset) with:
3476                 bool next_cell;
3477                 EntryDirection entry_from = ENTRY_DIRECTION_IGNORE;
3478                 FuncCode finish_lfun;
3479
3480                 if (cmd.action == LFUN_CHAR_FORWARD 
3481                                 || cmd.action == LFUN_CHAR_FORWARD_SELECT) {
3482                         next_cell = true;
3483                         finish_lfun = LFUN_FINISHED_FORWARD;
3484                 }
3485                 else if (cmd.action == LFUN_CHAR_BACKWARD
3486                                 || cmd.action == LFUN_CHAR_BACKWARD_SELECT) {
3487                         next_cell = false;
3488                         finish_lfun = LFUN_FINISHED_BACKWARD;
3489                 }
3490                 // LEFT or RIGHT commands --- the interpretation will depend on the 
3491                 // table's direction.
3492                 else {
3493                         bool const right = cmd.action == LFUN_CHAR_RIGHT
3494                                 || cmd.action == LFUN_CHAR_RIGHT_SELECT;
3495                         next_cell = isRightToLeft(cur) != right;
3496                         
3497                         if (lyxrc.visual_cursor)
3498                                 entry_from = right ? ENTRY_DIRECTION_LEFT:ENTRY_DIRECTION_RIGHT;
3499
3500                         finish_lfun = right ? LFUN_FINISHED_RIGHT : LFUN_FINISHED_LEFT;
3501                 }
3502
3503                 bool const select = cmd.action == LFUN_CHAR_FORWARD_SELECT ||
3504                     cmd.action == LFUN_CHAR_BACKWARD_SELECT ||
3505                     cmd.action == LFUN_CHAR_RIGHT_SELECT ||
3506                     cmd.action == LFUN_CHAR_LEFT_SELECT;
3507
3508                 // If we have a multicell selection or we're 
3509                 // not doing some LFUN_*_SELECT thing anyway...
3510                 if (!cur.selIsMultiCell() || !select) {
3511                         col_type const c = tabular.cellColumn(cur.idx());
3512                         row_type const r = tabular.cellRow(cur.idx());
3513                         // Are we trying to select the whole cell and is the whole cell 
3514                         // not yet selected?
3515                         bool const select_whole = select && !isCellSelected(cur, r, c) &&
3516                                 ((next_cell && cur.pit() == cur.lastpit() 
3517                                 && cur.pos() == cur.lastpos())
3518                                 || (!next_cell && cur.pit() == 0 && cur.pos() == 0));
3519
3520                         // ...try to dispatch to the cell's inset.
3521                         cell(cur.idx())->dispatch(cur, cmd);
3522
3523                         bool const empty_cell = cur.lastpos() == 0 && cur.lastpit() == 0;
3524                         
3525                         // When we already have a selection we want to select the whole cell
3526                         // before going to the next cell.
3527                         if (select_whole && !empty_cell){
3528                                 getText(cur.idx())->selectAll(cur);
3529                                 cur.dispatched();
3530                                 break;
3531                         }
3532
3533                         // FIXME: When we support the selection of an empty cell, remove 
3534                         // the !empty_cell from this condition. For now we jump to the next
3535                         // cell if the current cell is empty.
3536                         if (cur.result().dispatched() && !empty_cell)
3537                                 break;
3538                 }
3539
3540                 // move to next/prev cell, as appropriate
3541                 // note that we will always do this if we're selecting and we have
3542                 // a multicell selection
3543                 LYXERR(Debug::RTL, "entering " << (next_cell ? "next" : "previous")
3544                         << " cell from: " << int(entry_from));
3545                 if (next_cell)
3546                         moveNextCell(cur, entry_from);
3547                 else
3548                         movePrevCell(cur, entry_from);
3549                 // if we're exiting the table, call the appropriate FINISHED lfun
3550                 if (sl == cur.top())
3551                         cmd = FuncRequest(finish_lfun);
3552                 else
3553                         cur.dispatched();
3554                 break;
3555
3556         }
3557
3558         case LFUN_DOWN_SELECT:
3559         case LFUN_DOWN:
3560                 if (!(cur.selection() && cur.selIsMultiCell()))
3561                         cell(cur.idx())->dispatch(cur, cmd);
3562                 
3563                 cur.dispatched(); // override the cell's decision
3564                 if (sl == cur.top()) {
3565                         // if our Text didn't do anything to the cursor
3566                         // then we try to put the cursor into the cell below
3567                         // setting also the right targetX.
3568                         cur.selHandle(cmd.action == LFUN_DOWN_SELECT);
3569                         if (tabular.cellRow(cur.idx()) != tabular.row_info.size() - 1) {
3570                                 cur.idx() = tabular.cellBelow(cur.idx());
3571                                 cur.pit() = 0;
3572                                 TextMetrics const & tm =
3573                                         cur.bv().textMetrics(cell(cur.idx())->getText(0));
3574                                 cur.pos() = tm.x2pos(cur.pit(), 0, cur.targetX());
3575                         }
3576                 }
3577                 if (sl == cur.top()) {
3578                         // we trick it to go to forward after leaving the
3579                         // tabular.
3580                         cmd = FuncRequest(LFUN_FINISHED_FORWARD);
3581                         cur.undispatched();
3582                 }
3583                 if (cur.selIsMultiCell()) {
3584                         cur.pit() = cur.lastpit();
3585                         cur.pos() = cur.lastpos();
3586                         return;
3587                 }
3588                 break;
3589
3590         case LFUN_UP_SELECT:
3591         case LFUN_UP:
3592                 if (!(cur.selection() && cur.selIsMultiCell()))
3593                         cell(cur.idx())->dispatch(cur, cmd);
3594                 cur.dispatched(); // override the cell's decision
3595                 if (sl == cur.top()) {
3596                         // if our Text didn't do anything to the cursor
3597                         // then we try to put the cursor into the cell above
3598                         // setting also the right targetX.
3599                         cur.selHandle(cmd.action == LFUN_UP_SELECT);
3600                         if (tabular.cellRow(cur.idx()) != 0) {
3601                                 cur.idx() = tabular.cellAbove(cur.idx());
3602                                 cur.pit() = cur.lastpit();
3603                                 Text const * text = cell(cur.idx())->getText(0);
3604                                 TextMetrics const & tm = cur.bv().textMetrics(text);
3605                                 ParagraphMetrics const & pm =
3606                                         tm.parMetrics(cur.lastpit());
3607                                 cur.pos() = tm.x2pos(cur.pit(), pm.rows().size()-1, cur.targetX());
3608                         }
3609                 }
3610                 if (sl == cur.top()) {
3611                         cmd = FuncRequest(LFUN_UP);
3612                         cur.undispatched();
3613                 }
3614                 if (cur.selIsMultiCell()) {
3615                         cur.pit() = 0;
3616                         cur.pos() = cur.lastpos();
3617                         return;
3618                 }
3619                 break;
3620
3621 //      case LFUN_SCREEN_DOWN: {
3622 //              //if (hasSelection())
3623 //              //      cur.selection() = false;
3624 //              col_type const col = tabular.cellColumn(cur.idx());
3625 //              int const t =   cur.bv().top_y() + cur.bv().height();
3626 //              if (t < yo() + tabular.getHeightOfTabular()) {
3627 //                      cur.bv().scrollDocView(t);
3628 //                      cur.idx() = tabular.cellBelow(first_visible_cell) + col;
3629 //              } else {
3630 //                      cur.idx() = tabular.getFirstCellInRow(tabular.rows() - 1) + col;
3631 //              }
3632 //              cur.par() = 0;
3633 //              cur.pos() = 0;
3634 //              break;
3635 //      }
3636 //
3637 //      case LFUN_SCREEN_UP: {
3638 //              //if (hasSelection())
3639 //              //      cur.selection() = false;
3640 //              col_type const col = tabular.cellColumn(cur.idx());
3641 //              int const t =   cur.bv().top_y() + cur.bv().height();
3642 //              if (yo() < 0) {
3643 //                      cur.bv().scrollDocView(t);
3644 //                      if (yo() > 0)
3645 //                              cur.idx() = col;
3646 //                      else
3647 //                              cur.idx() = tabular.cellBelow(first_visible_cell) + col;
3648 //              } else {
3649 //                      cur.idx() = col;
3650 //              }
3651 //              cur.par() = cur.lastpar();
3652 //              cur.pos() = cur.lastpos();
3653 //              break;
3654 //      }
3655
3656         case LFUN_LAYOUT_TABULAR:
3657                 cur.bv().showDialog("tabular", params2string(*this), this);
3658                 break;
3659
3660         case LFUN_INSET_DIALOG_UPDATE:
3661                 cur.bv().updateDialog("tabular", params2string(*this));
3662                 break;
3663
3664         case LFUN_TABULAR_FEATURE:
3665                 if (!tabularFeatures(cur, to_utf8(cmd.argument())))
3666                         cur.undispatched();
3667                 break;
3668
3669         // insert file functions
3670         case LFUN_FILE_INSERT_PLAINTEXT_PARA:
3671         case LFUN_FILE_INSERT_PLAINTEXT:
3672                 // FIXME UNICODE
3673                 if (FileName::isAbsolute(to_utf8(cmd.argument()))) {
3674                         docstring const tmpstr = cur.bv().contentsOfPlaintextFile(
3675                                 FileName(to_utf8(cmd.argument())));
3676                         if (tmpstr.empty())
3677                                 break;
3678                         cur.recordUndoInset(INSERT_UNDO);
3679                         if (insertPlaintextString(cur.bv(), tmpstr, false)) {
3680                                 // content has been replaced,
3681                                 // so cursor might be invalid
3682                                 cur.pos() = cur.lastpos();
3683                                 cur.pit() = cur.lastpit();
3684                                 bvcur.setCursor(cur);
3685                         } else
3686                                 cur.undispatched();
3687                 }
3688                 break;
3689
3690         case LFUN_CUT:
3691                 if (cur.selIsMultiCell()) {
3692                         if (copySelection(cur)) {
3693                                 cur.recordUndoInset(DELETE_UNDO);
3694                                 cutSelection(cur);
3695                         }
3696                 } else
3697                         cell(cur.idx())->dispatch(cur, cmd);
3698                 break;
3699
3700         case LFUN_SELF_INSERT:
3701                 if (cur.selIsMultiCell()) {
3702                         cur.recordUndoInset(DELETE_UNDO);
3703                         cutSelection(cur);
3704                 }
3705                 cell(cur.idx())->dispatch(cur, cmd);
3706                 break;
3707
3708         case LFUN_CHAR_DELETE_BACKWARD:
3709         case LFUN_CHAR_DELETE_FORWARD:
3710                 if (cur.selIsMultiCell()) {
3711                         cur.recordUndoInset(DELETE_UNDO);
3712                         cutSelection(cur);
3713                 } else
3714                         cell(cur.idx())->dispatch(cur, cmd);
3715                 break;
3716
3717         case LFUN_COPY:
3718                 if (!cur.selection())
3719                         break;
3720                 if (cur.selIsMultiCell()) {
3721                         cur.finishUndo();
3722                         copySelection(cur);
3723                 } else
3724                         cell(cur.idx())->dispatch(cur, cmd);
3725                 break;
3726
3727         case LFUN_CLIPBOARD_PASTE:
3728         case LFUN_PRIMARY_SELECTION_PASTE: {
3729                 docstring const clip = (cmd.action == LFUN_CLIPBOARD_PASTE) ?
3730                         theClipboard().getAsText() :
3731                         theSelection().get();
3732                 if (clip.empty())
3733                         break;
3734                 // pass to InsertPlaintextString, but
3735                 // only if we have multi-cell content
3736                 if (clip.find_first_of(from_ascii("\t\n")) != docstring::npos) {
3737                         cur.recordUndoInset(INSERT_UNDO);
3738                         if (insertPlaintextString(cur.bv(), clip, false)) {
3739                                 // content has been replaced,
3740                                 // so cursor might be invalid
3741                                 cur.pos() = cur.lastpos();
3742                                 cur.pit() = cur.lastpit();
3743                                 bvcur.setCursor(cur);
3744                                 break;
3745                         }
3746                 }
3747                 // Let the cell handle normal text
3748                 cell(cur.idx())->dispatch(cur, cmd);
3749                 break;
3750         }
3751
3752         case LFUN_PASTE:
3753                 if (!tabularStackDirty()) {
3754                         if (!cur.selIsMultiCell())
3755                                 cell(cur.idx())->dispatch(cur, cmd);
3756                         break;
3757                 }
3758                 if (theClipboard().isInternal() ||
3759                     (!theClipboard().hasInternal() && theClipboard().hasLyXContents())) {
3760                         cur.recordUndoInset(INSERT_UNDO);
3761                         pasteClipboard(cur);
3762                 }
3763                 break;
3764
3765         case LFUN_FONT_EMPH:
3766         case LFUN_FONT_BOLD:
3767         case LFUN_FONT_BOLDSYMBOL:
3768         case LFUN_FONT_ROMAN:
3769         case LFUN_FONT_NOUN:
3770         case LFUN_FONT_ITAL:
3771         case LFUN_FONT_FRAK:
3772         case LFUN_FONT_TYPEWRITER:
3773         case LFUN_FONT_SANS:
3774         case LFUN_TEXTSTYLE_APPLY:
3775         case LFUN_TEXTSTYLE_UPDATE:
3776         case LFUN_FONT_SIZE:
3777         case LFUN_FONT_UNDERLINE:
3778         case LFUN_FONT_STRIKEOUT:
3779         case LFUN_FONT_UULINE:
3780         case LFUN_FONT_UWAVE:
3781         case LFUN_LANGUAGE:
3782         case LFUN_WORD_CAPITALIZE:
3783         case LFUN_WORD_UPCASE:
3784         case LFUN_WORD_LOWCASE:
3785         case LFUN_CHARS_TRANSPOSE:
3786                 if (cur.selIsMultiCell()) {
3787                         row_type rs, re;
3788                         col_type cs, ce;
3789                         getSelection(cur, rs, re, cs, ce);
3790                         Cursor tmpcur = cur;
3791                         for (row_type i = rs; i <= re; ++i) {
3792                                 for (col_type j = cs; j <= ce; ++j) {
3793                                         // cursor follows cell:
3794                                         tmpcur.idx() = tabular.cellIndex(i, j);
3795                                         // select this cell only:
3796                                         tmpcur.pit() = 0;
3797                                         tmpcur.pos() = 0;
3798                                         tmpcur.resetAnchor();
3799                                         tmpcur.pit() = tmpcur.lastpit();
3800                                         tmpcur.pos() = tmpcur.top().lastpos();
3801                                         tmpcur.setCursor(tmpcur);
3802                                         tmpcur.setSelection();
3803                                         cell(tmpcur.idx())->dispatch(tmpcur, cmd);
3804                                 }
3805                         }
3806                         break;
3807                 } else {
3808                         cell(cur.idx())->dispatch(cur, cmd);
3809                         break;
3810                 }
3811
3812         case LFUN_INSET_SETTINGS:
3813                 // relay this lfun to Inset, not to the cell.
3814                 Inset::doDispatch(cur, cmd);
3815                 break;
3816
3817         default:
3818                 // we try to handle this event in the insets dispatch function.
3819                 cell(cur.idx())->dispatch(cur, cmd);
3820                 break;
3821         }
3822 }
3823
3824
3825 // function sets an object as defined in func_status.h:
3826 // states OK, Unknown, Disabled, On, Off.
3827 bool InsetTabular::getStatus(Cursor & cur, FuncRequest const & cmd,
3828         FuncStatus & status) const
3829 {
3830         switch (cmd.action) {
3831         case LFUN_TABULAR_FEATURE: {
3832                 int action = Tabular::LAST_ACTION;
3833                 int i = 0;
3834                 for (; tabularFeature[i].action != Tabular::LAST_ACTION; ++i) {
3835                         string const tmp = tabularFeature[i].feature;
3836                         if (tmp == to_utf8(cmd.argument()).substr(0, tmp.length())) {
3837                                 action = tabularFeature[i].action;
3838                                 break;
3839                         }
3840                 }
3841                 if (action == Tabular::LAST_ACTION) {
3842                         status.clear();
3843                         status.unknown(true);
3844                         return true;
3845                 }
3846
3847                 string const argument
3848                         = ltrim(to_utf8(cmd.argument()).substr(tabularFeature[i].feature.length()));
3849
3850                 row_type sel_row_start = 0;
3851                 row_type sel_row_end = 0;
3852                 col_type sel_col_start = 0;
3853                 col_type sel_col_end = 0;
3854                 Tabular::ltType dummyltt;
3855                 bool flag = true;
3856
3857                 getSelection(cur, sel_row_start, sel_row_end, sel_col_start, sel_col_end);
3858
3859                 switch (action) {
3860                 case Tabular::SET_PWIDTH:
3861                 case Tabular::SET_MPWIDTH:
3862                 case Tabular::SET_SPECIAL_COLUMN:
3863                 case Tabular::SET_SPECIAL_MULTI:
3864                 case Tabular::APPEND_ROW:
3865                 case Tabular::APPEND_COLUMN:
3866                 case Tabular::DELETE_ROW:
3867                 case Tabular::DELETE_COLUMN:
3868                 case Tabular::COPY_ROW:
3869                 case Tabular::COPY_COLUMN:
3870                 case Tabular::SET_TOP_SPACE:
3871                 case Tabular::SET_BOTTOM_SPACE:
3872                 case Tabular::SET_INTERLINE_SPACE:
3873                         status.clear();
3874                         return true;
3875
3876                 case Tabular::MULTICOLUMN:
3877                         // If a row is set as longtable caption, it must not be allowed
3878                         // to unset that this row is a multicolumn.
3879                         status.setEnabled(sel_row_start == sel_row_end
3880                                 && !tabular.ltCaption(tabular.cellRow(cur.idx())));
3881                         status.setOnOff(tabular.isMultiColumn(cur.idx()));
3882                         break;
3883
3884                 case Tabular::SET_ALL_LINES:
3885                 case Tabular::UNSET_ALL_LINES:
3886                 case Tabular::SET_BORDER_LINES:
3887                         status.setEnabled(!tabular.ltCaption(tabular.cellRow(cur.idx())));
3888                         break;
3889
3890                 case Tabular::TOGGLE_LINE_TOP:
3891                         status.setEnabled(!tabular.ltCaption(tabular.cellRow(cur.idx())));
3892                         status.setOnOff(tabular.topLine(cur.idx()));
3893                         break;
3894
3895                 case Tabular::TOGGLE_LINE_BOTTOM:
3896                         status.setEnabled(!tabular.ltCaption(tabular.cellRow(cur.idx())));
3897                         status.setOnOff(tabular.bottomLine(cur.idx()));
3898                         break;
3899
3900                 case Tabular::TOGGLE_LINE_LEFT:
3901                         status.setEnabled(!tabular.ltCaption(tabular.cellRow(cur.idx())));
3902                         status.setOnOff(tabular.leftLine(cur.idx()));
3903                         break;
3904
3905                 case Tabular::TOGGLE_LINE_RIGHT:
3906                         status.setEnabled(!tabular.ltCaption(tabular.cellRow(cur.idx())));
3907                         status.setOnOff(tabular.rightLine(cur.idx()));
3908                         break;
3909
3910                 case Tabular::M_ALIGN_LEFT:
3911                         flag = false;
3912                 case Tabular::ALIGN_LEFT:
3913                         status.setOnOff(tabular.getAlignment(cur.idx(), flag) == LYX_ALIGN_LEFT);
3914                         break;
3915
3916                 case Tabular::M_ALIGN_RIGHT:
3917                         flag = false;
3918                 case Tabular::ALIGN_RIGHT:
3919                         status.setOnOff(tabular.getAlignment(cur.idx(), flag) == LYX_ALIGN_RIGHT);
3920                         break;
3921
3922                 case Tabular::M_ALIGN_CENTER:
3923                         flag = false;
3924                 case Tabular::ALIGN_CENTER:
3925                         status.setOnOff(tabular.getAlignment(cur.idx(), flag) == LYX_ALIGN_CENTER);
3926                         break;
3927
3928                 case Tabular::ALIGN_BLOCK:
3929                         status.setEnabled(!tabular.getPWidth(cur.idx()).zero());
3930                         status.setOnOff(tabular.getAlignment(cur.idx(), flag) == LYX_ALIGN_BLOCK);
3931                         break;
3932
3933                 case Tabular::M_VALIGN_TOP:
3934                         flag = false;
3935                 case Tabular::VALIGN_TOP:
3936                         status.setOnOff(
3937                                 tabular.getVAlignment(cur.idx(), flag) == Tabular::LYX_VALIGN_TOP);
3938                         break;
3939
3940                 case Tabular::M_VALIGN_BOTTOM:
3941                         flag = false;
3942                 case Tabular::VALIGN_BOTTOM:
3943                         status.setOnOff(
3944                                 tabular.getVAlignment(cur.idx(), flag) == Tabular::LYX_VALIGN_BOTTOM);
3945                         break;
3946
3947                 case Tabular::M_VALIGN_MIDDLE:
3948                         flag = false;
3949                 case Tabular::VALIGN_MIDDLE:
3950                         status.setOnOff(
3951                                 tabular.getVAlignment(cur.idx(), flag) == Tabular::LYX_VALIGN_MIDDLE);
3952                         break;
3953
3954                 case Tabular::SET_LONGTABULAR:
3955                         status.setOnOff(tabular.is_long_tabular);
3956                         break;
3957
3958                 case Tabular::UNSET_LONGTABULAR:
3959                         status.setOnOff(!tabular.is_long_tabular);
3960                         break;
3961
3962                 case Tabular::TOGGLE_ROTATE_TABULAR:
3963                 case Tabular::SET_ROTATE_TABULAR:
3964                         status.setOnOff(tabular.rotate);
3965                         break;
3966
3967                 case Tabular::TABULAR_VALIGN_TOP:
3968                         status.setOnOff(tabular.tabular_valignment 
3969                                 == Tabular::LYX_VALIGN_TOP);
3970                         break;
3971                 case Tabular::TABULAR_VALIGN_MIDDLE:
3972                         status.setOnOff(tabular.tabular_valignment 
3973                                 == Tabular::LYX_VALIGN_MIDDLE);
3974                         break;
3975                 case Tabular::TABULAR_VALIGN_BOTTOM:
3976                         status.setOnOff(tabular.tabular_valignment 
3977                                 == Tabular::LYX_VALIGN_BOTTOM);
3978                         break;
3979
3980                 case Tabular::LONGTABULAR_ALIGN_LEFT:
3981                         status.setOnOff(tabular.longtabular_alignment 
3982                                 == Tabular::LYX_LONGTABULAR_ALIGN_LEFT);
3983                         break;
3984                 case Tabular::LONGTABULAR_ALIGN_CENTER:
3985                         status.setOnOff(tabular.longtabular_alignment 
3986                                 == Tabular::LYX_LONGTABULAR_ALIGN_CENTER);
3987                         break;
3988                 case Tabular::LONGTABULAR_ALIGN_RIGHT:
3989                         status.setOnOff(tabular.longtabular_alignment 
3990                                 == Tabular::LYX_LONGTABULAR_ALIGN_RIGHT);
3991                         break;
3992
3993                 case Tabular::UNSET_ROTATE_TABULAR:
3994                         status.setOnOff(!tabular.rotate);
3995                         break;
3996
3997                 case Tabular::TOGGLE_ROTATE_CELL:
3998                 case Tabular::SET_ROTATE_CELL:
3999                         status.setOnOff(!oneCellHasRotationState(false,
4000                                 sel_row_start, sel_row_end, sel_col_start, sel_col_end));
4001                         break;
4002
4003                 case Tabular::UNSET_ROTATE_CELL:
4004                         status.setOnOff(!oneCellHasRotationState(true,
4005                                 sel_row_start, sel_row_end, sel_col_start, sel_col_end));
4006                         break;
4007
4008                 case Tabular::SET_USEBOX:
4009                         status.setOnOff(convert<int>(argument) == tabular.getUsebox(cur.idx()));
4010                         break;
4011
4012                 // every row can only be one thing:
4013                 // either a footer or header or caption
4014                 case Tabular::SET_LTFIRSTHEAD:
4015                         status.setEnabled(sel_row_start == sel_row_end
4016                                 && !tabular.ltCaption(sel_row_start));
4017                         status.setOnOff(tabular.getRowOfLTFirstHead(sel_row_start, dummyltt));
4018                         break;
4019
4020                 case Tabular::UNSET_LTFIRSTHEAD:
4021                         status.setOnOff(!tabular.getRowOfLTFirstHead(sel_row_start, dummyltt));
4022                         break;
4023
4024                 case Tabular::SET_LTHEAD:
4025                         status.setEnabled(sel_row_start == sel_row_end
4026                                 && !tabular.ltCaption(sel_row_start));
4027                         status.setOnOff(tabular.getRowOfLTHead(sel_row_start, dummyltt));
4028                         break;
4029
4030                 case Tabular::UNSET_LTHEAD:
4031                         status.setOnOff(!tabular.getRowOfLTHead(sel_row_start, dummyltt));
4032                         break;
4033
4034                 case Tabular::SET_LTFOOT:
4035                         status.setEnabled(sel_row_start == sel_row_end
4036                                 && !tabular.ltCaption(sel_row_start));
4037                         status.setOnOff(tabular.getRowOfLTFoot(sel_row_start, dummyltt));
4038                         break;
4039
4040                 case Tabular::UNSET_LTFOOT:
4041                         status.setOnOff(!tabular.getRowOfLTFoot(sel_row_start, dummyltt));
4042                         break;
4043
4044                 case Tabular::SET_LTLASTFOOT:
4045                         status.setEnabled(sel_row_start == sel_row_end
4046                                 && !tabular.ltCaption(sel_row_start));
4047                         status.setOnOff(tabular.getRowOfLTLastFoot(sel_row_start, dummyltt));
4048                         break;
4049
4050                 case Tabular::UNSET_LTLASTFOOT:
4051                         status.setOnOff(!tabular.getRowOfLTLastFoot(sel_row_start, dummyltt));
4052                         break;
4053
4054                 case Tabular::SET_LTNEWPAGE:
4055                         status.setOnOff(tabular.getLTNewPage(sel_row_start));
4056                         break;
4057
4058                 // only one row can be the caption
4059                 case Tabular::TOGGLE_LTCAPTION:
4060                         status.setEnabled(sel_row_start == sel_row_end
4061                                 && !tabular.getRowOfLTFirstHead(sel_row_start, dummyltt)
4062                                 && !tabular.getRowOfLTHead(sel_row_start, dummyltt)
4063                                 && !tabular.getRowOfLTFoot(sel_row_start, dummyltt)
4064                                 && !tabular.getRowOfLTLastFoot(sel_row_start, dummyltt)
4065                                 && (!tabular.haveLTCaption()
4066                                         || tabular.ltCaption(sel_row_start)));
4067                         status.setOnOff(tabular.ltCaption(sel_row_start));
4068                         break;
4069
4070                 case Tabular::SET_BOOKTABS:
4071                         status.setOnOff(tabular.use_booktabs);
4072                         break;
4073
4074                 case Tabular::UNSET_BOOKTABS:
4075                         status.setOnOff(!tabular.use_booktabs);
4076                         break;
4077
4078                 default:
4079                         status.clear();
4080                         status.setEnabled(false);
4081                         break;
4082                 }
4083                 return true;
4084         }
4085
4086         // These are only enabled inside tabular
4087         case LFUN_CELL_BACKWARD:
4088         case LFUN_CELL_FORWARD:
4089                 status.setEnabled(true);
4090                 return true;
4091
4092         // disable these with multiple cells selected
4093         case LFUN_INSET_INSERT:
4094         case LFUN_TABULAR_INSERT:
4095         case LFUN_FLEX_INSERT:
4096         case LFUN_FLOAT_INSERT:
4097         case LFUN_FLOAT_WIDE_INSERT:
4098         case LFUN_FOOTNOTE_INSERT:
4099         case LFUN_MARGINALNOTE_INSERT:
4100         case LFUN_MATH_INSERT:
4101         case LFUN_MATH_MODE:
4102         case LFUN_MATH_MUTATE:
4103         case LFUN_MATH_DISPLAY:
4104         case LFUN_NOTE_INSERT:
4105         case LFUN_OPTIONAL_INSERT:
4106         case LFUN_BOX_INSERT:
4107         case LFUN_BRANCH_INSERT:
4108         case LFUN_PHANTOM_INSERT:
4109         case LFUN_WRAP_INSERT:
4110         case LFUN_ERT_INSERT: {
4111                 if (cur.selIsMultiCell()) {
4112                         status.setEnabled(false);
4113                         return true;
4114                 } else
4115                         return cell(cur.idx())->getStatus(cur, cmd, status);
4116         }
4117
4118         // disable in non-fixed-width cells
4119         case LFUN_NEWLINE_INSERT:
4120         case LFUN_BREAK_PARAGRAPH: {
4121                 if (tabular.getPWidth(cur.idx()).zero()) {
4122                         status.setEnabled(false);
4123                         return true;
4124                 } else
4125                         return cell(cur.idx())->getStatus(cur, cmd, status);
4126         }
4127
4128         case LFUN_NEWPAGE_INSERT:
4129                 status.setEnabled(false);
4130                 return true;
4131
4132         case LFUN_PASTE:
4133                 if (tabularStackDirty() && theClipboard().isInternal()) {
4134                         if (cur.selIsMultiCell()) {
4135                                 row_type rs, re;
4136                                 col_type cs, ce;
4137                                 getSelection(cur, rs, re, cs, ce);
4138                                 if (paste_tabular && paste_tabular->column_info.size() == ce - cs + 1
4139                                           && paste_tabular->row_info.size() == re - rs + 1)
4140                                         status.setEnabled(true);        
4141                                 else {
4142                                         status.setEnabled(false);
4143                                         status.message(_("Selection size should match clipboard content."));
4144                                 }
4145                         } else
4146                                 status.setEnabled(true);
4147                         return true;
4148                 }
4149                 return cell(cur.idx())->getStatus(cur, cmd, status);
4150
4151         case LFUN_INSET_SETTINGS:
4152                 // relay this lfun to Inset, not to the cell.
4153                 return Inset::getStatus(cur, cmd, status);
4154
4155         case LFUN_INSET_MODIFY:
4156                 if (insetCode(cmd.getArg(0)) == TABULAR_CODE) {
4157                         status.setEnabled(true);
4158                         return true;
4159                 }
4160                 // Fall through
4161
4162         default:
4163                 // we try to handle this event in the insets dispatch function.
4164                 return cell(cur.idx())->getStatus(cur, cmd, status);
4165         }
4166 }
4167
4168
4169 Inset::DisplayType InsetTabular::display() const
4170 {
4171                 if (tabular.is_long_tabular) {
4172                         switch (tabular.longtabular_alignment) {
4173                         case Tabular::LYX_LONGTABULAR_ALIGN_LEFT:
4174                                 return AlignLeft;
4175                         case Tabular::LYX_LONGTABULAR_ALIGN_CENTER:
4176                                 return AlignCenter;
4177                         case Tabular::LYX_LONGTABULAR_ALIGN_RIGHT:
4178                                 return AlignRight;
4179                         default:
4180                                 return AlignCenter;
4181                         }
4182                 } else
4183                         return Inline;
4184 }
4185
4186
4187 int InsetTabular::latex(odocstream & os, OutputParams const & runparams) const
4188 {
4189         return tabular.latex(os, runparams);
4190 }
4191
4192
4193 int InsetTabular::plaintext(odocstream & os, OutputParams const & runparams) const
4194 {
4195         os << '\n'; // output table on a new line
4196         int const dp = runparams.linelen > 0 ? runparams.depth : 0;
4197         tabular.plaintext(os, runparams, dp, false, 0);
4198         return PLAINTEXT_NEWLINE;
4199 }
4200
4201
4202 int InsetTabular::docbook(odocstream & os, OutputParams const & runparams) const
4203 {
4204         int ret = 0;
4205         Inset * master = 0;
4206
4207         // FIXME: Why not pass a proper DocIterator here?
4208 #if 0
4209         // if the table is inside a float it doesn't need the informaltable
4210         // wrapper. Search for it.
4211         for (master = owner(); master; master = master->owner())
4212                 if (master->lyxCode() == FLOAT_CODE)
4213                         break;
4214 #endif
4215
4216         if (!master) {
4217                 os << "<informaltable>";
4218                 ++ret;
4219         }
4220         ret += tabular.docbook(os, runparams);
4221         if (!master) {
4222                 os << "</informaltable>";
4223                 ++ret;
4224         }
4225         return ret;
4226 }
4227
4228
4229 void InsetTabular::validate(LaTeXFeatures & features) const
4230 {
4231         tabular.validate(features);
4232 }
4233
4234
4235 shared_ptr<InsetTableCell const> InsetTabular::cell(idx_type idx) const
4236 {
4237         return tabular.cellInset(idx);
4238 }
4239
4240
4241 shared_ptr<InsetTableCell> InsetTabular::cell(idx_type idx)
4242 {
4243         return tabular.cellInset(idx);
4244 }
4245
4246
4247 void InsetTabular::cursorPos(BufferView const & bv,
4248                 CursorSlice const & sl, bool boundary, int & x, int & y) const
4249 {
4250         cell(sl.idx())->cursorPos(bv, sl, boundary, x, y);
4251
4252         // y offset     correction
4253         int const row = tabular.cellRow(sl.idx());
4254         for (int i = 0; i <= row; ++i) {
4255                 if (i != 0) {
4256                         y += tabular.rowAscent(i);
4257                         y += tabular.getAdditionalHeight(i);
4258                 }
4259                 if (i != row)
4260                         y += tabular.rowDescent(i);
4261         }
4262
4263         // x offset correction
4264         int const col = tabular.cellColumn(sl.idx());
4265         int idx = tabular.cellIndex(row, 0);
4266         for (int j = 0; j < col; ++j) {
4267                 if (tabular.isPartOfMultiColumn(row, j))
4268                         continue;
4269                 x += tabular.columnWidth(idx);
4270                 ++idx;
4271         }
4272         x += tabular.getBeginningOfTextInCell(idx);
4273         x += ADD_TO_TABULAR_WIDTH;
4274         x += scx_;
4275 }
4276
4277
4278 int InsetTabular::dist(BufferView & bv, idx_type const cell, int x, int y) const
4279 {
4280         int xx = 0;
4281         int yy = 0;
4282         Inset const & inset = *tabular.cellInset(cell);
4283         Point o = bv.coordCache().getInsets().xy(&inset);
4284         int const xbeg = o.x_ - tabular.getBeginningOfTextInCell(cell);
4285         int const xend = xbeg + tabular.columnWidth(cell);
4286         row_type const row = tabular.cellRow(cell);
4287         int const ybeg = o.y_ - tabular.rowAscent(row) -
4288                          tabular.getAdditionalHeight(row);
4289         int const yend = o.y_ + tabular.rowDescent(row);
4290
4291         if (x < xbeg)
4292                 xx = xbeg - x;
4293         else if (x > xend)
4294                 xx = x - xend;
4295
4296         if (y < ybeg)
4297                 yy = ybeg - y;
4298         else if (y > yend)
4299                 yy = y - yend;
4300
4301         //lyxerr << " xbeg=" << xbeg << "  xend=" << xend
4302         //       << " ybeg=" << ybeg << " yend=" << yend
4303         //       << " xx=" << xx << " yy=" << yy
4304         //       << " dist=" << xx + yy << endl;
4305         return xx + yy;
4306 }
4307
4308
4309 Inset * InsetTabular::editXY(Cursor & cur, int x, int y)
4310 {
4311         //lyxerr << "InsetTabular::editXY: " << this << endl;
4312         cur.setSelection(false);
4313         cur.push(*this);
4314         cur.idx() = getNearestCell(cur.bv(), x, y);
4315         resetPos(cur);
4316         return cur.bv().textMetrics(&cell(cur.idx())->text()).editXY(cur, x, y);
4317 }
4318
4319
4320 void InsetTabular::setCursorFromCoordinates(Cursor & cur, int x, int y) const
4321 {
4322         cur.idx() = getNearestCell(cur.bv(), x, y);
4323         cur.bv().textMetrics(&cell(cur.idx())->text()).setCursorFromCoordinates(cur, x, y);
4324 }
4325
4326
4327 InsetTabular::idx_type InsetTabular::getNearestCell(BufferView & bv, int x, int y) const
4328 {
4329         idx_type idx_min = 0;
4330         int dist_min = numeric_limits<int>::max();
4331         for (idx_type i = 0, n = nargs(); i != n; ++i) {
4332                 if (bv.coordCache().getInsets().has(tabular.cellInset(i).get())) {
4333                         int const d = dist(bv, i, x, y);
4334                         if (d < dist_min) {
4335                                 dist_min = d;
4336                                 idx_min = i;
4337                         }
4338                 }
4339         }
4340         return idx_min;
4341 }
4342
4343
4344 int InsetTabular::cellXPos(idx_type const cell) const
4345 {
4346         idx_type c = cell;
4347
4348         for (; !tabular.isFirstCellInRow(c); --c)
4349                 ;
4350         int lx = 0;
4351         for (; c < cell; ++c)
4352                 lx += tabular.columnWidth(c);
4353
4354         return lx;
4355 }
4356
4357
4358 void InsetTabular::resetPos(Cursor & cur) const
4359 {
4360         BufferView & bv = cur.bv();
4361         int const maxwidth = bv.workWidth();
4362
4363         int const scx_old = scx_;
4364         int const i = cur.find(this);
4365         if (i == -1) {
4366                 scx_ = 0;
4367         } else {
4368                 int const X1 = 0;
4369                 int const X2 = maxwidth;
4370                 int const offset = ADD_TO_TABULAR_WIDTH + 2;
4371                 int const x1 = xo(cur.bv()) + cellXPos(cur[i].idx()) + offset;
4372                 int const x2 = x1 + tabular.columnWidth(cur[i].idx());
4373
4374                 if (x1 < X1)
4375                         scx_ = X1 + 20 - x1;
4376                 else if (x2 > X2)
4377                         scx_ = X2 - 20 - x2;
4378                 else
4379                         scx_ = 0;
4380         }
4381
4382         // only update if offset changed
4383         if (scx_ != scx_old)
4384                 cur.updateFlags(Update::Force | Update::FitCursor);
4385 }
4386
4387
4388 void InsetTabular::moveNextCell(Cursor & cur, EntryDirection entry_from)
4389 {
4390         if (isRightToLeft(cur)) {
4391                 if (tabular.isFirstCellInRow(cur.idx())) {
4392                         row_type const row = tabular.cellRow(cur.idx());
4393                         if (row == tabular.row_info.size() - 1)
4394                                 return;
4395                         cur.idx() = tabular.cellBelow(tabular.getLastCellInRow(row));
4396                 } else {
4397                         if (cur.idx() == 0)
4398                                 return;
4399                         --cur.idx();
4400                 }
4401         } else {
4402                 if (tabular.isLastCell(cur.idx()))
4403                         return;
4404                 ++cur.idx();
4405         }
4406
4407         cur.boundary(false);
4408
4409         if (cur.selIsMultiCell()) {
4410                 cur.pit() = cur.lastpit();
4411                 cur.pos() = cur.lastpos();
4412                 resetPos(cur);
4413                 return;
4414         }
4415
4416         cur.pit() = 0;
4417         cur.pos() = 0;
4418
4419         // in visual mode, place cursor at extreme left or right
4420         
4421         switch(entry_from) {
4422
4423         case ENTRY_DIRECTION_RIGHT:
4424                 cur.posVisToRowExtremity(false /* !left */);
4425                 break;
4426         case ENTRY_DIRECTION_LEFT:
4427                 cur.posVisToRowExtremity(true /* left */);
4428                 break;
4429         case ENTRY_DIRECTION_IGNORE:
4430                 // nothing to do in this case
4431                 break;
4432
4433         }
4434
4435         resetPos(cur);
4436 }
4437
4438
4439 void InsetTabular::movePrevCell(Cursor & cur, EntryDirection entry_from)
4440 {
4441         if (isRightToLeft(cur)) {
4442                 if (tabular.isLastCellInRow(cur.idx())) {
4443                         row_type const row = tabular.cellRow(cur.idx());
4444                         if (row == 0)
4445                                 return;
4446                         cur.idx() = tabular.getFirstCellInRow(row);
4447                         cur.idx() = tabular.cellAbove(cur.idx());
4448                 } else {
4449                         if (tabular.isLastCell(cur.idx()))
4450                                 return;
4451                         ++cur.idx();
4452                 }
4453         } else {
4454                 if (cur.idx() == 0) // first cell
4455                         return;
4456                 --cur.idx();
4457         }
4458
4459         if (cur.selIsMultiCell()) {
4460                 cur.pit() = cur.lastpit();
4461                 cur.pos() = cur.lastpos();
4462                 resetPos(cur);
4463                 return;
4464         }
4465
4466         cur.pit() = cur.lastpit();
4467         cur.pos() = cur.lastpos();
4468
4469         // in visual mode, place cursor at extreme left or right
4470         
4471         switch(entry_from) {
4472
4473         case ENTRY_DIRECTION_RIGHT:
4474                 cur.posVisToRowExtremity(false /* !left */);
4475                 break;
4476         case ENTRY_DIRECTION_LEFT:
4477                 cur.posVisToRowExtremity(true /* left */);
4478                 break;
4479         case ENTRY_DIRECTION_IGNORE:
4480                 // nothing to do in this case
4481                 break;
4482
4483         }
4484
4485         resetPos(cur);
4486 }
4487
4488
4489 bool InsetTabular::tabularFeatures(Cursor & cur, string const & what)
4490 {
4491         Tabular::Feature action = Tabular::LAST_ACTION;
4492
4493         int i = 0;
4494         for (; tabularFeature[i].action != Tabular::LAST_ACTION; ++i) {
4495                 string const tmp = tabularFeature[i].feature;
4496
4497                 if (tmp == what.substr(0, tmp.length())) {
4498                         //if (!compare(tabularFeatures[i].feature.c_str(), what.c_str(),
4499                         //tabularFeatures[i].feature.length()))
4500                         action = tabularFeature[i].action;
4501                         break;
4502                 }
4503         }
4504         if (action == Tabular::LAST_ACTION)
4505                 return false;
4506
4507         string const val =
4508                 ltrim(what.substr(tabularFeature[i].feature.length()));
4509         tabularFeatures(cur, action, val);
4510         return true;
4511 }
4512
4513
4514 static void checkLongtableSpecial(Tabular::ltType & ltt,
4515                           string const & special, bool & flag)
4516 {
4517         if (special == "dl_above") {
4518                 ltt.topDL = flag;
4519                 ltt.set = false;
4520         } else if (special == "dl_below") {
4521                 ltt.bottomDL = flag;
4522                 ltt.set = false;
4523         } else if (special == "empty") {
4524                 ltt.empty = flag;
4525                 ltt.set = false;
4526         } else if (flag) {
4527                 ltt.empty = false;
4528                 ltt.set = true;
4529         }
4530 }
4531
4532 bool InsetTabular::oneCellHasRotationState(bool rotated,
4533                 row_type row_start, row_type row_end,
4534                 col_type col_start, col_type col_end) const {
4535
4536         for (row_type i = row_start; i <= row_end; ++i) {
4537                 for (col_type j = col_start; j <= col_end; ++j) {
4538                         if (tabular.getRotateCell(tabular.cellIndex(i, j))
4539                                 == rotated) {
4540                                 return true;
4541                         }
4542                 }
4543         }
4544         return false;
4545 }
4546
4547 void InsetTabular::tabularFeatures(Cursor & cur,
4548         Tabular::Feature feature, string const & value)
4549 {
4550         col_type sel_col_start;
4551         col_type sel_col_end;
4552         row_type sel_row_start;
4553         row_type sel_row_end;
4554         bool setLines = false;
4555         LyXAlignment setAlign = LYX_ALIGN_LEFT;
4556         Tabular::VAlignment setVAlign = Tabular::LYX_VALIGN_TOP;
4557
4558         switch (feature) {
4559
4560         case Tabular::M_ALIGN_LEFT:
4561         case Tabular::ALIGN_LEFT:
4562                 setAlign = LYX_ALIGN_LEFT;
4563                 break;
4564
4565         case Tabular::M_ALIGN_RIGHT:
4566         case Tabular::ALIGN_RIGHT:
4567                 setAlign = LYX_ALIGN_RIGHT;
4568                 break;
4569
4570         case Tabular::M_ALIGN_CENTER:
4571         case Tabular::ALIGN_CENTER:
4572                 setAlign = LYX_ALIGN_CENTER;
4573                 break;
4574
4575         case Tabular::ALIGN_BLOCK:
4576                 setAlign = LYX_ALIGN_BLOCK;
4577                 break;
4578
4579         case Tabular::M_VALIGN_TOP:
4580         case Tabular::VALIGN_TOP:
4581                 setVAlign = Tabular::LYX_VALIGN_TOP;
4582                 break;
4583
4584         case Tabular::M_VALIGN_BOTTOM:
4585         case Tabular::VALIGN_BOTTOM:
4586                 setVAlign = Tabular::LYX_VALIGN_BOTTOM;
4587                 break;
4588
4589         case Tabular::M_VALIGN_MIDDLE:
4590         case Tabular::VALIGN_MIDDLE:
4591                 setVAlign = Tabular::LYX_VALIGN_MIDDLE;
4592                 break;
4593
4594         default:
4595                 break;
4596         }
4597
4598         cur.recordUndoInset(ATOMIC_UNDO);
4599
4600         getSelection(cur, sel_row_start, sel_row_end, sel_col_start, sel_col_end);
4601         row_type const row = tabular.cellRow(cur.idx());
4602         col_type const column = tabular.cellColumn(cur.idx());
4603         bool flag = true;
4604         Tabular::ltType ltt;
4605
4606         switch (feature) {
4607
4608         case Tabular::SET_PWIDTH: {
4609                 Length const len(value);
4610                 tabular.setColumnPWidth(cur, cur.idx(), len);
4611                 if (len.zero()
4612                     && tabular.getAlignment(cur.idx(), true) == LYX_ALIGN_BLOCK)
4613                         tabularFeatures(cur, Tabular::ALIGN_CENTER, string());
4614                 break;
4615         }
4616
4617         case Tabular::SET_MPWIDTH:
4618                 tabular.setMColumnPWidth(cur, cur.idx(), Length(value));
4619                 break;
4620
4621         case Tabular::SET_SPECIAL_COLUMN:
4622         case Tabular::SET_SPECIAL_MULTI:
4623                 tabular.setAlignSpecial(cur.idx(), from_utf8(value), feature);
4624                 break;
4625
4626         case Tabular::APPEND_ROW:
4627                 // append the row into the tabular
4628                 tabular.appendRow(cur.idx());
4629                 break;
4630
4631         case Tabular::APPEND_COLUMN:
4632                 // append the column into the tabular
4633                 tabular.appendColumn(cur.idx());
4634                 cur.idx() = tabular.cellIndex(row, column);
4635                 break;
4636
4637         case Tabular::DELETE_ROW:
4638                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4639                         tabular.deleteRow(sel_row_start);
4640                 if (sel_row_start >= tabular.row_info.size())
4641                         --sel_row_start;
4642                 cur.idx() = tabular.cellIndex(sel_row_start, column);
4643                 cur.pit() = 0;
4644                 cur.pos() = 0;
4645                 cur.setSelection(false);
4646                 break;
4647
4648         case Tabular::DELETE_COLUMN:
4649                 for (col_type i = sel_col_start; i <= sel_col_end; ++i)
4650                         tabular.deleteColumn(sel_col_start);
4651                 if (sel_col_start >= tabular.column_info.size())
4652                         --sel_col_start;
4653                 cur.idx() = tabular.cellIndex(row, sel_col_start);
4654                 cur.pit() = 0;
4655                 cur.pos() = 0;
4656                 cur.setSelection(false);
4657                 break;
4658
4659         case Tabular::COPY_ROW:
4660                 tabular.copyRow(row);
4661                 break;
4662
4663         case Tabular::COPY_COLUMN:
4664                 tabular.copyColumn(column);
4665                 cur.idx() = tabular.cellIndex(row, column);
4666                 break;
4667
4668         case Tabular::TOGGLE_LINE_TOP: {
4669                 bool lineSet = !tabular.topLine(cur.idx());
4670                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4671                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
4672                                 tabular.setTopLine(tabular.cellIndex(i, j), lineSet);
4673                 break;
4674         }
4675
4676         case Tabular::TOGGLE_LINE_BOTTOM: {
4677                 bool lineSet = !tabular.bottomLine(cur.idx());
4678                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4679                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
4680                                 tabular.setBottomLine(tabular.cellIndex(i, j), lineSet);
4681                 break;
4682         }
4683
4684         case Tabular::TOGGLE_LINE_LEFT: {
4685                 bool lineSet = !tabular.leftLine(cur.idx());
4686                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4687                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
4688                                 tabular.setLeftLine(tabular.cellIndex(i, j), lineSet);
4689                 break;
4690         }
4691
4692         case Tabular::TOGGLE_LINE_RIGHT: {
4693                 bool lineSet = !tabular.rightLine(cur.idx());
4694                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4695                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
4696                                 tabular.setRightLine(tabular.cellIndex(i, j), lineSet);
4697                 break;
4698         }
4699
4700         case Tabular::M_ALIGN_LEFT:
4701         case Tabular::M_ALIGN_RIGHT:
4702         case Tabular::M_ALIGN_CENTER:
4703                 flag = false;
4704         case Tabular::ALIGN_LEFT:
4705         case Tabular::ALIGN_RIGHT:
4706         case Tabular::ALIGN_CENTER:
4707         case Tabular::ALIGN_BLOCK:
4708                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4709                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
4710                                 tabular.setAlignment(tabular.cellIndex(i, j), setAlign, flag);
4711                 break;
4712
4713         case Tabular::M_VALIGN_TOP:
4714         case Tabular::M_VALIGN_BOTTOM:
4715         case Tabular::M_VALIGN_MIDDLE:
4716                 flag = false;
4717         case Tabular::VALIGN_TOP:
4718         case Tabular::VALIGN_BOTTOM:
4719         case Tabular::VALIGN_MIDDLE:
4720                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4721                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
4722                                 tabular.setVAlignment(tabular.cellIndex(i, j), setVAlign, flag);
4723                 break;
4724
4725         case Tabular::MULTICOLUMN: {
4726                 if (!cur.selection()) {
4727                         // just multicol for one single cell
4728                         // check whether we are completely in a multicol
4729                         if (tabular.isMultiColumn(cur.idx()))
4730                                 tabular.unsetMultiColumn(cur.idx());
4731                         else
4732                                 tabular.setMultiColumn(cur.idx(), 1);
4733                         break;
4734                 }
4735                 // we have a selection so this means we just add all this
4736                 // cells to form a multicolumn cell
4737                 idx_type const s_start = cur.selBegin().idx();
4738                 idx_type const s_end = cur.selEnd().idx();
4739                 tabular.setMultiColumn(s_start, s_end - s_start + 1);
4740                 cur.idx() = s_start;
4741                 cur.pit() = 0;
4742                 cur.pos() = 0;
4743                 cur.setSelection(false);
4744                 break;
4745         }
4746
4747         case Tabular::SET_ALL_LINES:
4748                 setLines = true;
4749         case Tabular::UNSET_ALL_LINES:
4750                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4751                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
4752                                 tabular.setAllLines(
4753                                         tabular.cellIndex(i,j), setLines);
4754                 break;
4755
4756         case Tabular::SET_BORDER_LINES:
4757                 for (row_type i = sel_row_start; i <= sel_row_end; ++i) {
4758                         tabular.setLeftLine(tabular.cellIndex(i, sel_col_start), true);
4759                         tabular.setRightLine(tabular.cellIndex(i, sel_col_end), true);
4760                 }
4761                 for (col_type j = sel_col_start; j <= sel_col_end; ++j) {
4762                         tabular.setTopLine(tabular.cellIndex(sel_row_start, j), true);
4763                         tabular.setBottomLine(tabular.cellIndex(sel_row_end, j), true);
4764                 }
4765                 break;
4766
4767         case Tabular::SET_LONGTABULAR:
4768                 tabular.is_long_tabular = true;
4769                 break;
4770
4771         case Tabular::UNSET_LONGTABULAR:
4772                 tabular.is_long_tabular = false;
4773                 break;
4774
4775         case Tabular::SET_ROTATE_TABULAR:
4776                 tabular.rotate = true;
4777                 break;
4778
4779         case Tabular::UNSET_ROTATE_TABULAR:
4780                 tabular.rotate = false;
4781                 break;
4782
4783         case Tabular::TOGGLE_ROTATE_TABULAR:
4784                 tabular.rotate = !tabular.rotate;
4785                 break;
4786
4787         case Tabular::TABULAR_VALIGN_TOP:
4788                 tabular.tabular_valignment = Tabular::LYX_VALIGN_TOP;
4789                 break;
4790
4791         case Tabular::TABULAR_VALIGN_MIDDLE:
4792                 tabular.tabular_valignment = Tabular::LYX_VALIGN_MIDDLE;
4793                 break;
4794
4795         case Tabular::TABULAR_VALIGN_BOTTOM:
4796                 tabular.tabular_valignment = Tabular::LYX_VALIGN_BOTTOM;
4797                 break;
4798
4799         case Tabular::LONGTABULAR_ALIGN_LEFT:
4800                 tabular.longtabular_alignment = Tabular::LYX_LONGTABULAR_ALIGN_LEFT;
4801                 break;
4802
4803         case Tabular::LONGTABULAR_ALIGN_CENTER:
4804                 tabular.longtabular_alignment = Tabular::LYX_LONGTABULAR_ALIGN_CENTER;
4805                 break;
4806
4807         case Tabular::LONGTABULAR_ALIGN_RIGHT:
4808                 tabular.longtabular_alignment = Tabular::LYX_LONGTABULAR_ALIGN_RIGHT;
4809                 break;
4810
4811                 
4812
4813         case Tabular::SET_ROTATE_CELL:
4814                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4815                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
4816                                 tabular.setRotateCell(
4817                                         tabular.cellIndex(i, j), true);
4818                 break;
4819
4820         case Tabular::UNSET_ROTATE_CELL:
4821                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4822                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
4823                                 tabular.setRotateCell(tabular.cellIndex(i, j), false);
4824                 break;
4825
4826         case Tabular::TOGGLE_ROTATE_CELL:
4827                 {
4828                 bool oneNotRotated = oneCellHasRotationState(false,
4829                         sel_row_start, sel_row_end, sel_col_start, sel_col_end);
4830
4831                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4832                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
4833                                 tabular.setRotateCell(tabular.cellIndex(i, j),
4834                                                                           oneNotRotated);
4835                 }
4836                 break;
4837
4838         case Tabular::SET_USEBOX: {
4839                 Tabular::BoxType val = Tabular::BoxType(convert<int>(value));
4840                 if (val == tabular.getUsebox(cur.idx()))
4841                         val = Tabular::BOX_NONE;
4842                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4843                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
4844                                 tabular.setUsebox(tabular.cellIndex(i, j), val);
4845                 break;
4846         }
4847
4848         case Tabular::UNSET_LTFIRSTHEAD:
4849                 flag = false;
4850         case Tabular::SET_LTFIRSTHEAD:
4851                 tabular.getRowOfLTFirstHead(row, ltt);
4852                 checkLongtableSpecial(ltt, value, flag);
4853                 tabular.setLTHead(row, flag, ltt, true);
4854                 break;
4855
4856         case Tabular::UNSET_LTHEAD:
4857                 flag = false;
4858         case Tabular::SET_LTHEAD:
4859                 tabular.getRowOfLTHead(row, ltt);
4860                 checkLongtableSpecial(ltt, value, flag);
4861                 tabular.setLTHead(row, flag, ltt, false);
4862                 break;
4863
4864         case Tabular::UNSET_LTFOOT:
4865                 flag = false;
4866         case Tabular::SET_LTFOOT:
4867                 tabular.getRowOfLTFoot(row, ltt);
4868                 checkLongtableSpecial(ltt, value, flag);
4869                 tabular.setLTFoot(row, flag, ltt, false);
4870                 break;
4871
4872         case Tabular::UNSET_LTLASTFOOT:
4873                 flag = false;
4874         case Tabular::SET_LTLASTFOOT:
4875                 tabular.getRowOfLTLastFoot(row, ltt);
4876                 checkLongtableSpecial(ltt, value, flag);
4877                 tabular.setLTFoot(row, flag, ltt, true);
4878                 break;
4879
4880         case Tabular::SET_LTNEWPAGE:
4881                 tabular.setLTNewPage(row, !tabular.getLTNewPage(row));
4882                 break;
4883
4884         case Tabular::TOGGLE_LTCAPTION: {
4885                 bool set = !tabular.ltCaption(row);
4886                 cur.idx() = tabular.setLTCaption(row, set);
4887                 cur.pit() = 0;
4888                 cur.pos() = 0;
4889                 cur.setSelection(false);
4890                 // When a row is set as caption, then also insert a caption. Otherwise
4891                 // the LaTeX output is broken, when the user doesn't add a caption.
4892                 if (set)
4893                         lyx::dispatch(FuncRequest(LFUN_CAPTION_INSERT));
4894                 break;
4895         }
4896
4897         case Tabular::SET_BOOKTABS:
4898                 tabular.use_booktabs = true;
4899                 break;
4900
4901         case Tabular::UNSET_BOOKTABS:
4902                 tabular.use_booktabs = false;
4903                 break;
4904
4905         case Tabular::SET_TOP_SPACE: {
4906                 Length len;
4907                 if (value == "default")
4908                         for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4909                                 tabular.row_info[i].top_space_default = true;
4910                 else if (isValidLength(value, &len))
4911                         for (row_type i = sel_row_start; i <= sel_row_end; ++i) {
4912                                 tabular.row_info[i].top_space_default = false;
4913                                 tabular.row_info[i].top_space = len;
4914                         }
4915                 else
4916                         for (row_type i = sel_row_start; i <= sel_row_end; ++i) {
4917                                 tabular.row_info[i].top_space_default = false;
4918                                 tabular.row_info[i].top_space = len;
4919                         }
4920                 break;
4921         }
4922
4923         case Tabular::SET_BOTTOM_SPACE: {
4924                 Length len;
4925                 if (value == "default")
4926                         for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4927                                 tabular.row_info[i].bottom_space_default = true;
4928                 else if (isValidLength(value, &len))
4929                         for (row_type i = sel_row_start; i <= sel_row_end; ++i) {
4930                                 tabular.row_info[i].bottom_space_default = false;
4931                                 tabular.row_info[i].bottom_space = len;
4932                         }
4933                 else
4934                         for (row_type i = sel_row_start; i <= sel_row_end; ++i) {
4935                                 tabular.row_info[i].bottom_space_default = false;
4936                                 tabular.row_info[i].bottom_space = len;
4937                         }
4938                 break;
4939         }
4940
4941         case Tabular::SET_INTERLINE_SPACE: {
4942                 Length len;
4943                 if (value == "default")
4944                         for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4945                                 tabular.row_info[i].interline_space_default = true;
4946                 else if (isValidLength(value, &len))
4947                         for (row_type i = sel_row_start; i <= sel_row_end; ++i) {
4948                                 tabular.row_info[i].interline_space_default = false;
4949                                 tabular.row_info[i].interline_space = len;
4950                         }
4951                 else
4952                         for (row_type i = sel_row_start; i <= sel_row_end; ++i) {
4953                                 tabular.row_info[i].interline_space_default = false;
4954                                 tabular.row_info[i].interline_space = len;
4955                         }
4956                 break;
4957         }
4958
4959         // dummy stuff just to avoid warnings
4960         case Tabular::LAST_ACTION:
4961                 break;
4962         }
4963 }
4964
4965
4966 bool InsetTabular::showInsetDialog(BufferView * bv) const
4967 {
4968         bv->showDialog("tabular", params2string(*this),
4969                 const_cast<InsetTabular *>(this));
4970         return true;
4971 }
4972
4973
4974 void InsetTabular::openLayoutDialog(BufferView * bv) const
4975 {
4976         bv->showDialog("tabular", params2string(*this),
4977                 const_cast<InsetTabular *>(this));
4978 }
4979
4980
4981 bool InsetTabular::copySelection(Cursor & cur)
4982 {
4983         if (!cur.selection())
4984                 return false;
4985
4986         row_type rs, re;
4987         col_type cs, ce;
4988         getSelection(cur, rs, re, cs, ce);
4989
4990         paste_tabular.reset(new Tabular(tabular));
4991
4992         for (row_type i = 0; i < rs; ++i)
4993                 paste_tabular->deleteRow(0);
4994
4995         row_type const rows = re - rs + 1;
4996         while (paste_tabular->row_info.size() > rows)
4997                 paste_tabular->deleteRow(rows);
4998
4999         for (col_type i = 0; i < cs; ++i)
5000                 paste_tabular->deleteColumn(0);
5001
5002         col_type const columns = ce - cs + 1;
5003         while (paste_tabular->column_info.size() > columns)
5004                 paste_tabular->deleteColumn(columns);
5005
5006         paste_tabular->setBuffer(tabular.buffer());
5007
5008         odocstringstream os;
5009         OutputParams const runparams(0);
5010         paste_tabular->plaintext(os, runparams, 0, true, '\t');
5011         // Needed for the "Edit->Paste recent" menu and the system clipboard.
5012         cap::copySelection(cur, os.str());
5013
5014         // mark tabular stack dirty
5015         // FIXME: this is a workaround for bug 1919. Should be removed for 1.5,
5016         // when we (hopefully) have a one-for-all paste mechanism.
5017         // This must be called after cap::copySelection.
5018         dirtyTabularStack(true);
5019
5020         return true;
5021 }
5022
5023
5024 bool InsetTabular::pasteClipboard(Cursor & cur)
5025 {
5026         if (!paste_tabular)
5027                 return false;
5028         col_type actcol = tabular.cellColumn(cur.idx());
5029         row_type actrow = tabular.cellRow(cur.idx());
5030
5031         if (cur.selIsMultiCell()) {
5032                 row_type re;
5033                 col_type ce;
5034                 getSelection(cur, actrow, re, actcol, ce);
5035         }
5036
5037         for (row_type r1 = 0, r2 = actrow;
5038              r1 < paste_tabular->row_info.size() && r2 < tabular.row_info.size();
5039              ++r1, ++r2) {
5040                 for (col_type c1 = 0, c2 = actcol;
5041                     c1 < paste_tabular->column_info.size() && c2 < tabular.column_info.size();
5042                     ++c1, ++c2) {
5043                         if (paste_tabular->isPartOfMultiColumn(r1, c1) &&
5044                               tabular.isPartOfMultiColumn(r2, c2))
5045                                 continue;
5046                         if (paste_tabular->isPartOfMultiColumn(r1, c1)) {
5047                                 --c2;
5048                                 continue;
5049                         }
5050                         if (tabular.isPartOfMultiColumn(r2, c2)) {
5051                                 --c1;
5052                                 continue;
5053                         }
5054                         shared_ptr<InsetTableCell> inset(
5055                                 new InsetTableCell(*paste_tabular->cellInset(r1, c1)));
5056                         tabular.setCellInset(r2, c2, inset);
5057                         // FIXME: change tracking (MG)
5058                         inset->setChange(Change(buffer().params().trackChanges ?
5059                                                 Change::INSERTED : Change::UNCHANGED));
5060                         cur.pos() = 0;
5061                 }
5062         }
5063         return true;
5064 }
5065
5066
5067 void InsetTabular::cutSelection(Cursor & cur)
5068 {
5069         if (!cur.selection())
5070                 return;
5071
5072         row_type rs, re;
5073         col_type cs, ce;
5074         getSelection(cur, rs, re, cs, ce);
5075         for (row_type i = rs; i <= re; ++i) {
5076                 for (col_type j = cs; j <= ce; ++j) {
5077                         shared_ptr<InsetTableCell> t
5078                                 = cell(tabular.cellIndex(i, j));
5079                         if (buffer().params().trackChanges)
5080                                 // FIXME: Change tracking (MG)
5081                                 t->setChange(Change(Change::DELETED));
5082                         else
5083                                 t->clear();
5084                 }
5085         }
5086
5087         // cursor position might be invalid now
5088         if (cur.pit() > cur.lastpit())
5089                 cur.pit() = cur.lastpit();
5090         if (cur.pos() > cur.lastpos())
5091                 cur.pos() = cur.lastpos();
5092         cur.clearSelection();
5093 }
5094
5095
5096 bool InsetTabular::isRightToLeft(Cursor & cur) const
5097 {
5098         LASSERT(cur.depth() > 1, /**/);
5099         Paragraph const & parentpar = cur[cur.depth() - 2].paragraph();
5100         pos_type const parentpos = cur[cur.depth() - 2].pos();
5101         return parentpar.getFontSettings(buffer().params(),
5102                                          parentpos).language()->rightToLeft();
5103 }
5104
5105 docstring InsetTabular::asString(idx_type stidx, idx_type enidx, 
5106                                  bool intoInsets)
5107 {
5108         LASSERT(stidx <= enidx, return docstring());
5109         docstring retval;
5110         col_type const col1 = tabular.cellColumn(stidx);
5111         col_type const col2 = tabular.cellColumn(enidx);
5112         row_type const row1 = tabular.cellRow(stidx);
5113         row_type const row2 = tabular.cellRow(enidx);
5114         bool first = true;
5115         for (col_type col = col1; col <= col2; col++)
5116                 for (row_type row = row1; row <= row2; row++) {
5117                         if (!first)
5118                                 retval += "\n";
5119                         else
5120                                 first = false;
5121                         retval += tabular.cellInset(row, col)->asString(intoInsets);
5122                 }
5123         return retval;
5124 }
5125
5126
5127 void InsetTabular::getSelection(Cursor & cur,
5128         row_type & rs, row_type & re, col_type & cs, col_type & ce) const
5129 {
5130         CursorSlice const & beg = cur.selBegin();
5131         CursorSlice const & end = cur.selEnd();
5132         cs = tabular.cellColumn(beg.idx());
5133         ce = tabular.cellColumn(end.idx());
5134         if (cs > ce) {
5135                 ce = cs;
5136                 cs = tabular.cellColumn(end.idx());
5137         } else {
5138                 ce = tabular.cellRightColumn(end.idx());
5139         }
5140
5141         rs = tabular.cellRow(beg.idx());
5142         re = tabular.cellRow(end.idx());
5143         if (rs > re)
5144                 swap(rs, re);
5145 }
5146
5147
5148 Text * InsetTabular::getText(int idx) const
5149 {
5150         return size_t(idx) < nargs() ? cell(idx)->getText(0) : 0;
5151 }
5152
5153
5154 void InsetTabular::setChange(Change const & change)
5155 {
5156         for (idx_type idx = 0; idx < nargs(); ++idx)
5157                 cell(idx)->setChange(change);
5158 }
5159
5160
5161 void InsetTabular::acceptChanges()
5162 {
5163         for (idx_type idx = 0; idx < nargs(); ++idx)
5164                 cell(idx)->acceptChanges();
5165 }
5166
5167
5168 void InsetTabular::rejectChanges()
5169 {
5170         for (idx_type idx = 0; idx < nargs(); ++idx)
5171                 cell(idx)->rejectChanges();
5172 }
5173
5174
5175 bool InsetTabular::allowParagraphCustomization(idx_type cell) const
5176 {
5177         return tabular.getPWidth(cell).zero();
5178 }
5179
5180
5181 bool InsetTabular::forcePlainLayout(idx_type cell) const
5182 {
5183         return !tabular.getPWidth(cell).zero();
5184 }
5185
5186
5187 bool InsetTabular::insertPlaintextString(BufferView & bv, docstring const & buf,
5188                                      bool usePaste)
5189 {
5190         if (buf.length() <= 0)
5191                 return true;
5192
5193         col_type cols = 1;
5194         row_type rows = 1;
5195         col_type maxCols = 1;
5196         size_t const len = buf.length();
5197         size_t p = 0;
5198
5199         while (p < len &&
5200                (p = buf.find_first_of(from_ascii("\t\n"), p)) != docstring::npos) {
5201                 switch (buf[p]) {
5202                 case '\t':
5203                         ++cols;
5204                         break;
5205                 case '\n':
5206                         if (p + 1 < len)
5207                                 ++rows;
5208                         maxCols = max(cols, maxCols);
5209                         cols = 1;
5210                         break;
5211                 }
5212                 ++p;
5213         }
5214         maxCols = max(cols, maxCols);
5215         Tabular * loctab;
5216         idx_type cell = 0;
5217         col_type ocol = 0;
5218         row_type row = 0;
5219         if (usePaste) {
5220                 paste_tabular.reset(new Tabular(buffer(), rows, maxCols));
5221                 loctab = paste_tabular.get();
5222                 cols = 0;
5223                 dirtyTabularStack(true);
5224         } else {
5225                 loctab = &tabular;
5226                 cell = bv.cursor().idx();
5227                 ocol = tabular.cellColumn(cell);
5228                 row = tabular.cellRow(cell);
5229         }
5230
5231         size_t op = 0;
5232         idx_type const cells = loctab->numberofcells;
5233         p = 0;
5234         cols = ocol;
5235         rows = loctab->row_info.size();
5236         col_type const columns = loctab->column_info.size();
5237
5238         while (cell < cells && p < len && row < rows &&
5239                (p = buf.find_first_of(from_ascii("\t\n"), p)) != docstring::npos)
5240         {
5241                 if (p >= len)
5242                         break;
5243                 switch (buf[p]) {
5244                 case '\t':
5245                         // we can only set this if we are not too far right
5246                         if (cols < columns) {
5247                                 shared_ptr<InsetTableCell> inset = loctab->cellInset(cell);
5248                                 Font const font = bv.textMetrics(&inset->text()).
5249                                         displayFont(0, 0);
5250                                 inset->setText(buf.substr(op, p - op), font,
5251                                                buffer().params().trackChanges);
5252                                 ++cols;
5253                                 ++cell;
5254                         }
5255                         break;
5256                 case '\n':
5257                         // we can only set this if we are not too far right
5258                         if (cols < columns) {
5259                                 shared_ptr<InsetTableCell> inset = tabular.cellInset(cell);
5260                                 Font const font = bv.textMetrics(&inset->text()).
5261                                         displayFont(0, 0);
5262                                 inset->setText(buf.substr(op, p - op), font,
5263                                                buffer().params().trackChanges);
5264                         }
5265                         cols = ocol;
5266                         ++row;
5267                         if (row < rows)
5268                                 cell = loctab->cellIndex(row, cols);
5269                         break;
5270                 }
5271                 ++p;
5272                 op = p;
5273         }
5274         // check for the last cell if there is no trailing '\n'
5275         if (cell < cells && op < len) {
5276                 shared_ptr<InsetTableCell> inset = loctab->cellInset(cell);
5277                 Font const font = bv.textMetrics(&inset->text()).displayFont(0, 0);
5278                 inset->setText(buf.substr(op, len - op), font,
5279                         buffer().params().trackChanges);
5280         }
5281         return true;
5282 }
5283
5284
5285 void InsetTabular::addPreview(PreviewLoader & loader) const
5286 {
5287         row_type const rows = tabular.row_info.size();
5288         col_type const columns = tabular.column_info.size();
5289         for (row_type i = 0; i < rows; ++i) {
5290                 for (col_type j = 0; j < columns; ++j)
5291                         tabular.cellInset(i, j)->addPreview(loader);
5292         }
5293 }
5294
5295
5296 bool InsetTabular::completionSupported(Cursor const & cur) const
5297 {
5298         Cursor const & bvCur = cur.bv().cursor();
5299         if (&bvCur.inset() != this)
5300                 return false;
5301         return cur.text()->completionSupported(cur);
5302 }
5303
5304
5305 bool InsetTabular::inlineCompletionSupported(Cursor const & cur) const
5306 {
5307         return completionSupported(cur);
5308 }
5309
5310
5311 bool InsetTabular::automaticInlineCompletion() const
5312 {
5313         return lyxrc.completion_inline_text;
5314 }
5315
5316
5317 bool InsetTabular::automaticPopupCompletion() const
5318 {
5319         return lyxrc.completion_popup_text;
5320 }
5321
5322
5323 bool InsetTabular::showCompletionCursor() const
5324 {
5325         return lyxrc.completion_cursor_text;
5326 }
5327
5328
5329 CompletionList const * InsetTabular::createCompletionList(Cursor const & cur) const
5330 {
5331         return completionSupported(cur) ? cur.text()->createCompletionList(cur) : 0;
5332 }
5333
5334
5335 docstring InsetTabular::completionPrefix(Cursor const & cur) const
5336 {
5337         if (!completionSupported(cur))
5338                 return docstring();
5339         return cur.text()->completionPrefix(cur);
5340 }
5341
5342
5343 bool InsetTabular::insertCompletion(Cursor & cur, docstring const & s, bool finished)
5344 {
5345         if (!completionSupported(cur))
5346                 return false;
5347
5348         return cur.text()->insertCompletion(cur, s, finished);
5349 }
5350
5351
5352 void InsetTabular::completionPosAndDim(Cursor const & cur, int & x, int & y, 
5353                                     Dimension & dim) const
5354 {
5355         TextMetrics const & tm = cur.bv().textMetrics(cur.text());
5356         tm.completionPosAndDim(cur, x, y, dim);
5357 }
5358
5359
5360 void InsetTabular::string2params(string const & in, InsetTabular & inset)
5361 {
5362         istringstream data(in);
5363         Lexer lex;
5364         lex.setStream(data);
5365
5366         if (in.empty())
5367                 return;
5368
5369         string token;
5370         lex >> token;
5371         if (!lex || token != "tabular") {
5372                 LYXERR0("Expected arg 1 to be \"tabular\" in " << in);
5373                 return;
5374         }
5375
5376         // This is part of the inset proper that is usually swallowed
5377         // by Buffer::readInset
5378         lex >> token;
5379         if (!lex || token != "Tabular") {
5380                 LYXERR0("Expected arg 2 to be \"Tabular\" in " << in);
5381                 return;
5382         }
5383
5384         inset.read(lex);
5385 }
5386
5387
5388 string InsetTabular::params2string(InsetTabular const & inset)
5389 {
5390         ostringstream data;
5391         data << "tabular" << ' ';
5392         inset.write(data);
5393         data << "\\end_inset\n";
5394         return data.str();
5395 }
5396
5397
5398 } // namespace lyx