]> git.lyx.org Git - lyx.git/blob - src/insets/InsetTabular.cpp
Move the contents of a row into the caption when setting a row as a longtable caption.
[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.h"
42 #include "ParagraphParameters.h"
43 #include "ParIterator.h"
44 #include "TextClass.h"
45 #include "TextMetrics.h"
46
47 #include "frontends/Application.h"
48 #include "frontends/alert.h"
49 #include "frontends/Clipboard.h"
50 #include "frontends/Painter.h"
51 #include "frontends/Selection.h"
52
53 #include "support/convert.h"
54 #include "support/debug.h"
55 #include "support/docstream.h"
56 #include "support/FileName.h"
57 #include "support/gettext.h"
58 #include "support/lassert.h"
59 #include "support/lstrings.h"
60
61 #include <boost/scoped_ptr.hpp>
62
63 #include <sstream>
64 #include <iostream>
65 #include <limits>
66 #include <cstring>
67
68 using namespace std;
69 using namespace lyx::support;
70
71 using boost::shared_ptr;
72 using boost::dynamic_pointer_cast;
73
74
75 namespace lyx {
76
77 using cap::dirtyTabularStack;
78 using cap::tabularStackDirty;
79
80 using graphics::PreviewLoader;
81
82 using frontend::Painter;
83 using frontend::Clipboard;
84
85 namespace Alert = frontend::Alert;
86
87
88 namespace {
89
90 int const ADD_TO_HEIGHT = 2; // in cell
91 int const ADD_TO_TABULAR_WIDTH = 6; // horiz space before and after the table
92 int const default_line_space = 10; // ?
93 int const WIDTH_OF_LINE = 5; // space between double lines
94
95
96 ///
97 boost::scoped_ptr<Tabular> paste_tabular;
98
99
100 struct TabularFeature {
101         Tabular::Feature action;
102         string feature;
103 };
104
105
106 TabularFeature tabularFeature[] =
107 {
108         { Tabular::APPEND_ROW, "append-row" },
109         { Tabular::APPEND_COLUMN, "append-column" },
110         { Tabular::DELETE_ROW, "delete-row" },
111         { Tabular::DELETE_COLUMN, "delete-column" },
112         { Tabular::COPY_ROW, "copy-row" },
113         { Tabular::COPY_COLUMN, "copy-column" },
114         { Tabular::TOGGLE_LINE_TOP, "toggle-line-top" },
115         { Tabular::TOGGLE_LINE_BOTTOM, "toggle-line-bottom" },
116         { Tabular::TOGGLE_LINE_LEFT, "toggle-line-left" },
117         { Tabular::TOGGLE_LINE_RIGHT, "toggle-line-right" },
118         { Tabular::ALIGN_LEFT, "align-left" },
119         { Tabular::ALIGN_RIGHT, "align-right" },
120         { Tabular::ALIGN_CENTER, "align-center" },
121         { Tabular::ALIGN_BLOCK, "align-block" },
122         { Tabular::VALIGN_TOP, "valign-top" },
123         { Tabular::VALIGN_BOTTOM, "valign-bottom" },
124         { Tabular::VALIGN_MIDDLE, "valign-middle" },
125         { Tabular::M_ALIGN_LEFT, "m-align-left" },
126         { Tabular::M_ALIGN_RIGHT, "m-align-right" },
127         { Tabular::M_ALIGN_CENTER, "m-align-center" },
128         { Tabular::M_VALIGN_TOP, "m-valign-top" },
129         { Tabular::M_VALIGN_BOTTOM, "m-valign-bottom" },
130         { Tabular::M_VALIGN_MIDDLE, "m-valign-middle" },
131         { Tabular::MULTICOLUMN, "multicolumn" },
132         { Tabular::SET_ALL_LINES, "set-all-lines" },
133         { Tabular::UNSET_ALL_LINES, "unset-all-lines" },
134         { Tabular::SET_LONGTABULAR, "set-longtabular" },
135         { Tabular::UNSET_LONGTABULAR, "unset-longtabular" },
136         { Tabular::SET_PWIDTH, "set-pwidth" },
137         { Tabular::SET_MPWIDTH, "set-mpwidth" },
138         { Tabular::SET_ROTATE_TABULAR, "set-rotate-tabular" },
139         { Tabular::UNSET_ROTATE_TABULAR, "unset-rotate-tabular" },
140         { Tabular::TOGGLE_ROTATE_TABULAR, "toggle-rotate-tabular" },
141         { Tabular::SET_ROTATE_CELL, "set-rotate-cell" },
142         { Tabular::UNSET_ROTATE_CELL, "unset-rotate-cell" },
143         { Tabular::TOGGLE_ROTATE_CELL, "toggle-rotate-cell" },
144         { Tabular::SET_USEBOX, "set-usebox" },
145         { Tabular::SET_LTHEAD, "set-lthead" },
146         { Tabular::UNSET_LTHEAD, "unset-lthead" },
147         { Tabular::SET_LTFIRSTHEAD, "set-ltfirsthead" },
148         { Tabular::UNSET_LTFIRSTHEAD, "unset-ltfirsthead" },
149         { Tabular::SET_LTFOOT, "set-ltfoot" },
150         { Tabular::UNSET_LTFOOT, "unset-ltfoot" },
151         { Tabular::SET_LTLASTFOOT, "set-ltlastfoot" },
152         { Tabular::UNSET_LTLASTFOOT, "unset-ltlastfoot" },
153         { Tabular::SET_LTNEWPAGE, "set-ltnewpage" },
154         { Tabular::TOGGLE_LTCAPTION, "toggle-ltcaption" },
155         { Tabular::SET_SPECIAL_COLUMN, "set-special-column" },
156         { Tabular::SET_SPECIAL_MULTI, "set-special-multi" },
157         { Tabular::SET_BOOKTABS, "set-booktabs" },
158         { Tabular::UNSET_BOOKTABS, "unset-booktabs" },
159         { Tabular::SET_TOP_SPACE, "set-top-space" },
160         { Tabular::SET_BOTTOM_SPACE, "set-bottom-space" },
161         { Tabular::SET_INTERLINE_SPACE, "set-interline-space" },
162         { Tabular::SET_BORDER_LINES, "set-border-lines" },
163         { Tabular::TABULAR_VALIGN_TOP, "tabular-valign-top"},
164         { Tabular::TABULAR_VALIGN_MIDDLE, "tabular-valign-middle"},
165         { Tabular::TABULAR_VALIGN_BOTTOM, "tabular-valign-bottom"},
166         { Tabular::LONGTABULAR_ALIGN_LEFT, "longtabular-align-left" },
167         { Tabular::LONGTABULAR_ALIGN_CENTER, "longtabular-align-center" },
168         { Tabular::LONGTABULAR_ALIGN_RIGHT, "longtabular-align-right" },        
169         { Tabular::LAST_ACTION, "" }
170 };
171
172
173 class FeatureEqual : public unary_function<TabularFeature, bool> {
174 public:
175         FeatureEqual(Tabular::Feature feature)
176                 : feature_(feature) {}
177         bool operator()(TabularFeature const & tf) const {
178                 return tf.action == feature_;
179         }
180 private:
181         Tabular::Feature feature_;
182 };
183
184
185 template <class T>
186 string const write_attribute(string const & name, T const & t)
187 {
188         string const s = tostr(t);
189         return s.empty() ? s : " " + name + "=\"" + s + "\"";
190 }
191
192 template <>
193 string const write_attribute(string const & name, string const & t)
194 {
195         return t.empty() ? t : " " + name + "=\"" + t + "\"";
196 }
197
198
199 template <>
200 string const write_attribute(string const & name, docstring const & t)
201 {
202         return t.empty() ? string() : " " + name + "=\"" + to_utf8(t) + "\"";
203 }
204
205
206 template <>
207 string const write_attribute(string const & name, bool const & b)
208 {
209         // we write only true attribute values so we remove a bit of the
210         // file format bloat for tabulars.
211         return b ? write_attribute(name, convert<string>(b)) : string();
212 }
213
214
215 template <>
216 string const write_attribute(string const & name, int const & i)
217 {
218         // we write only true attribute values so we remove a bit of the
219         // file format bloat for tabulars.
220         return i ? write_attribute(name, convert<string>(i)) : string();
221 }
222
223
224 template <>
225 string const write_attribute(string const & name, Tabular::idx_type const & i)
226 {
227         // we write only true attribute values so we remove a bit of the
228         // file format bloat for tabulars.
229         return i ? write_attribute(name, convert<string>(i)) : string();
230 }
231
232
233 template <>
234 string const write_attribute(string const & name, Length const & value)
235 {
236         // we write only the value if we really have one same reson as above.
237         return value.zero() ? string() : write_attribute(name, value.asString());
238 }
239
240
241 string const tostr(LyXAlignment const & num)
242 {
243         switch (num) {
244         case LYX_ALIGN_NONE:
245                 return "none";
246         case LYX_ALIGN_BLOCK:
247                 return "block";
248         case LYX_ALIGN_LEFT:
249                 return "left";
250         case LYX_ALIGN_CENTER:
251                 return "center";
252         case LYX_ALIGN_RIGHT:
253                 return "right";
254         case LYX_ALIGN_LAYOUT:
255                 return "layout";
256         case LYX_ALIGN_SPECIAL:
257                 return "special";
258         }
259         return string();
260 }
261
262
263 string const tostr(Tabular::HAlignment const & num)
264 {
265         switch (num) {
266         case Tabular::LYX_LONGTABULAR_ALIGN_LEFT:
267                 return "left";
268         case Tabular::LYX_LONGTABULAR_ALIGN_CENTER:
269                 return "center";
270         case Tabular::LYX_LONGTABULAR_ALIGN_RIGHT:
271                 return "right";
272         }
273         return string();
274 }
275
276
277 string const tostr(Tabular::VAlignment const & num)
278 {
279         switch (num) {
280         case Tabular::LYX_VALIGN_TOP:
281                 return "top";
282         case Tabular::LYX_VALIGN_MIDDLE:
283                 return "middle";
284         case Tabular::LYX_VALIGN_BOTTOM:
285                 return "bottom";
286         }
287         return string();
288 }
289
290
291 string const tostr(Tabular::BoxType const & num)
292 {
293         switch (num) {
294         case Tabular::BOX_NONE:
295                 return "none";
296         case Tabular::BOX_PARBOX:
297                 return "parbox";
298         case Tabular::BOX_MINIPAGE:
299                 return "minipage";
300         }
301         return string();
302 }
303
304
305 // I would have liked a fromstr template a lot better. (Lgb)
306 bool string2type(string const str, LyXAlignment & num)
307 {
308         if (str == "none")
309                 num = LYX_ALIGN_NONE;
310         else if (str == "block")
311                 num = LYX_ALIGN_BLOCK;
312         else if (str == "left")
313                 num = LYX_ALIGN_LEFT;
314         else if (str == "center")
315                 num = LYX_ALIGN_CENTER;
316         else if (str == "right")
317                 num = LYX_ALIGN_RIGHT;
318         else
319                 return false;
320         return true;
321 }
322
323
324 bool string2type(string const str, Tabular::HAlignment & num)
325 {
326         if (str == "left")
327                 num = Tabular::LYX_LONGTABULAR_ALIGN_LEFT;
328         else if (str == "center" )
329                 num = Tabular::LYX_LONGTABULAR_ALIGN_CENTER;
330         else if (str == "right")
331                 num = Tabular::LYX_LONGTABULAR_ALIGN_RIGHT;
332         else
333                 return false;
334         return true;
335 }
336
337
338 bool string2type(string const str, Tabular::VAlignment & num)
339 {
340         if (str == "top")
341                 num = Tabular::LYX_VALIGN_TOP;
342         else if (str == "middle" )
343                 num = Tabular::LYX_VALIGN_MIDDLE;
344         else if (str == "bottom")
345                 num = Tabular::LYX_VALIGN_BOTTOM;
346         else
347                 return false;
348         return true;
349 }
350
351
352 bool string2type(string const str, Tabular::BoxType & num)
353 {
354         if (str == "none")
355                 num = Tabular::BOX_NONE;
356         else if (str == "parbox")
357                 num = Tabular::BOX_PARBOX;
358         else if (str == "minipage")
359                 num = Tabular::BOX_MINIPAGE;
360         else
361                 return false;
362         return true;
363 }
364
365
366 bool string2type(string const str, bool & num)
367 {
368         if (str == "true")
369                 num = true;
370         else if (str == "false")
371                 num = false;
372         else
373                 return false;
374         return true;
375 }
376
377
378 bool getTokenValue(string const & str, char const * token, string & ret)
379 {
380         ret.erase();
381         size_t token_length = strlen(token);
382         size_t pos = str.find(token);
383
384         if (pos == string::npos || pos + token_length + 1 >= str.length()
385                 || str[pos + token_length] != '=')
386                 return false;
387         pos += token_length + 1;
388         char ch = str[pos];
389         if (ch != '"' && ch != '\'') { // only read till next space
390                 ret += ch;
391                 ch = ' ';
392         }
393         while (pos < str.length() - 1 && str[++pos] != ch)
394                 ret += str[pos];
395
396         return true;
397 }
398
399
400 bool getTokenValue(string const & str, char const * token, docstring & ret)
401 {
402         string tmp;
403         bool const success = getTokenValue(str, token, tmp);
404         ret = from_utf8(tmp);
405         return success;
406 }
407
408
409 bool getTokenValue(string const & str, char const * token, int & num)
410 {
411         string tmp;
412         num = 0;
413         if (!getTokenValue(str, token, tmp))
414                 return false;
415         num = convert<int>(tmp);
416         return true;
417 }
418
419
420 bool getTokenValue(string const & str, char const * token, LyXAlignment & num)
421 {
422         string tmp;
423         return getTokenValue(str, token, tmp) && string2type(tmp, num);
424 }
425
426
427 bool getTokenValue(string const & str, char const * token,
428                                    Tabular::HAlignment & num)
429 {
430         string tmp;
431         return getTokenValue(str, token, tmp) && string2type(tmp, num);
432 }
433
434
435 bool getTokenValue(string const & str, char const * token,
436                                    Tabular::VAlignment & num)
437 {
438         string tmp;
439         return getTokenValue(str, token, tmp) && string2type(tmp, num);
440 }
441
442
443 bool getTokenValue(string const & str, char const * token,
444                                    Tabular::BoxType & num)
445 {
446         string tmp;
447         return getTokenValue(str, token, tmp) && string2type(tmp, num);
448 }
449
450
451 bool getTokenValue(string const & str, char const * token, bool & flag)
452 {
453         // set the flag always to false as this should be the default for bools
454         // not in the file-format.
455         flag = false;
456         string tmp;
457         return getTokenValue(str, token, tmp) && string2type(tmp, flag);
458 }
459
460
461 bool getTokenValue(string const & str, char const * token, Length & len)
462 {
463         // set the length to be zero() as default as this it should be if not
464         // in the file format.
465         len = Length();
466         string tmp;
467         return getTokenValue(str, token, tmp) && isValidLength(tmp, &len);
468 }
469
470
471 bool getTokenValue(string const & str, char const * token, Length & len, bool & flag)
472 {
473         len = Length();
474         flag = false;
475         string tmp;
476         if (!getTokenValue(str, token, tmp))
477                 return false;
478         if (tmp == "default") {
479                 flag = true;
480                 return  true;
481         }
482         return isValidLength(tmp, &len);
483 }
484
485
486 void l_getline(istream & is, string & str)
487 {
488         str.erase();
489         while (str.empty()) {
490                 getline(is, str);
491                 if (!str.empty() && str[str.length() - 1] == '\r')
492                         str.erase(str.length() - 1);
493         }
494 }
495
496 } // namespace
497
498
499 string const featureAsString(Tabular::Feature feature)
500 {
501         TabularFeature * end = tabularFeature +
502                 sizeof(tabularFeature) / sizeof(TabularFeature);
503         TabularFeature * it = find_if(tabularFeature, end,
504                                            FeatureEqual(feature));
505         return (it == end) ? string() : it->feature;
506 }
507
508
509
510 /////////////////////////////////////////////////////////////////////
511 //
512 // Tabular
513 //
514 /////////////////////////////////////////////////////////////////////
515
516
517 Tabular::CellData::CellData(Buffer * buf)
518         : cellno(0),
519           width(0),
520           multicolumn(Tabular::CELL_NORMAL),
521           alignment(LYX_ALIGN_CENTER),
522           valignment(LYX_VALIGN_TOP),
523           top_line(false),
524           bottom_line(false),
525           left_line(false),
526           right_line(false),
527           usebox(BOX_NONE),
528           rotate(false),
529           inset(new InsetTableCell(buf))
530 {
531         inset->setBuffer(*buf);
532 }
533
534
535 Tabular::CellData::CellData(CellData const & cs)
536         : cellno(cs.cellno),
537           width(cs.width),
538           multicolumn(cs.multicolumn),
539           alignment(cs.alignment),
540           valignment(cs.valignment),
541           top_line(cs.top_line),
542           bottom_line(cs.bottom_line),
543           left_line(cs.left_line),
544           right_line(cs.right_line),
545           usebox(cs.usebox),
546           rotate(cs.rotate),
547           align_special(cs.align_special),
548           p_width(cs.p_width),
549           inset(dynamic_cast<InsetTableCell *>(cs.inset->clone()))
550 {
551 }
552
553 Tabular::CellData & Tabular::CellData::operator=(CellData cs)
554 {
555         swap(cs);
556         return *this;
557 }
558
559 void Tabular::CellData::swap(CellData & rhs)
560 {
561         std::swap(cellno, rhs.cellno);
562         std::swap(width, rhs.width);
563         std::swap(multicolumn, rhs.multicolumn);
564         std::swap(alignment, rhs.alignment);
565         std::swap(valignment, rhs.valignment);
566         std::swap(top_line, rhs.top_line);
567         std::swap(bottom_line, rhs.bottom_line);
568         std::swap(left_line, rhs.left_line);
569         std::swap(right_line, rhs.right_line);
570         std::swap(usebox, rhs.usebox);
571         std::swap(rotate, rhs.rotate);
572         std::swap(align_special, rhs.align_special);
573         p_width.swap(rhs.p_width);
574         inset.swap(rhs.inset);
575 }
576
577
578 Tabular::RowData::RowData()
579         : ascent(0),
580           descent(0),
581           top_space_default(false),
582           bottom_space_default(false),
583           interline_space_default(false),
584           endhead(false),
585           endfirsthead(false),
586           endfoot(false),
587           endlastfoot(false),
588           newpage(false),
589           caption(false)
590 {}
591
592
593 Tabular::ColumnData::ColumnData()
594         : alignment(LYX_ALIGN_CENTER),
595           valignment(LYX_VALIGN_TOP),
596           width(0)
597 {
598 }
599
600
601 Tabular::ltType::ltType()
602         : topDL(false),
603           bottomDL(false),
604           empty(false)
605 {}
606
607
608 Tabular::Tabular(Buffer * buffer, row_type rows_arg, col_type columns_arg)
609 {
610         init(buffer, rows_arg, columns_arg);
611 }
612
613
614 void Tabular::setBuffer(Buffer & buffer)
615 {
616         buffer_ = &buffer;
617         size_t row_count = row_info.size();
618         size_t column_count = column_info.size();
619         // set silly default lines
620         for (row_type i = 0; i < row_count; ++i)
621                 for (col_type j = 0; j < column_count; ++j)
622                         cell_info[i][j].inset->setBuffer(*buffer_);
623 }
624
625
626 // activates all lines and sets all widths to 0
627 void Tabular::init(Buffer * buf, row_type rows_arg,
628                       col_type columns_arg)
629 {
630         buffer_ = buf;
631         row_info = row_vector(rows_arg);
632         column_info = column_vector(columns_arg);
633         cell_info = cell_vvector(rows_arg, cell_vector(columns_arg, CellData(buf)));
634         row_info.reserve(10);
635         column_info.reserve(10);
636         cell_info.reserve(100);
637         updateIndexes();
638         is_long_tabular = false;
639         tabular_valignment = LYX_VALIGN_MIDDLE;
640         longtabular_alignment = LYX_LONGTABULAR_ALIGN_CENTER;
641         rotate = false;
642         use_booktabs = false;
643         size_t row_count = row_info.size();
644         size_t column_count = column_info.size();
645         // set silly default lines
646         for (row_type i = 0; i < row_count; ++i)
647                 for (col_type j = 0; j < column_count; ++j) {
648                         cell_info[i][j].inset->setBuffer(*buffer_);
649                         cell_info[i][j].top_line = true;
650                         cell_info[i][j].left_line = true;
651                         cell_info[i][j].bottom_line = i == 0 || i == row_count - 1;
652                         cell_info[i][j].right_line = j == column_count - 1;
653                 }
654 }
655
656
657 void Tabular::appendRow(idx_type const cell)
658 {
659         BufferParams const & bp = buffer_->params();
660         row_type const row = cellRow(cell);
661
662         row_vector::iterator rit = row_info.begin() + row;
663         row_info.insert(rit, RowData());
664         // now set the values of the row before
665         row_info[row] = row_info[row + 1];
666
667         row_type const nrows = row_info.size();
668         col_type const ncols = column_info.size();
669
670         cell_vvector old(nrows - 1);
671         for (row_type i = 0; i < nrows - 1; ++i)
672                 swap(cell_info[i], old[i]);
673
674         cell_info = cell_vvector(nrows, cell_vector(ncols, CellData(buffer_)));
675
676         for (row_type i = 0; i <= row; ++i)
677                 swap(cell_info[i], old[i]);
678         for (row_type i = row + 2; i < nrows; ++i)
679                 swap(cell_info[i], old[i - 1]);
680
681         updateIndexes();
682         for (col_type c = 0; c < ncols; ++c) {
683                 // inherit line settings
684                 idx_type const i = cellIndex(row + 1, c);
685                 idx_type const j = cellIndex(row, c);
686                 setLeftLine(i, leftLine(j));
687                 setRightLine(i, rightLine(j));
688                 setTopLine(i, topLine(j));
689                 if (topLine(j) && bottomLine(j)) {
690                         setBottomLine(i, true);
691                         setBottomLine(j, false);
692                 }
693                 // mark track changes
694                 if (bp.trackChanges)
695                         cellInfo(i).inset->setChange(Change(Change::INSERTED));
696         }
697 }
698
699
700 void Tabular::deleteRow(row_type const row)
701 {
702         // Not allowed to delete last row
703         if (row_info.size() == 1)
704                 return;
705
706         row_info.erase(row_info.begin() + row);
707         cell_info.erase(cell_info.begin() + row);
708         updateIndexes();
709 }
710
711
712 void Tabular::copyRow(row_type const row)
713 {
714         row_info.insert(row_info.begin() + row, row_info[row]);
715         cell_info.insert(cell_info.begin() + row, cell_info[row]);
716
717         if (buffer().params().trackChanges)
718                 for (col_type j = 0; j < column_info.size(); ++j)
719                         cell_info[row + 1][j].inset->setChange(Change(Change::INSERTED));
720
721         updateIndexes();
722 }
723
724
725 void Tabular::appendColumn(idx_type const cell)
726 {
727         col_type const c = cellColumn(cell);
728         column_vector::iterator cit = column_info.begin() + c + 1;
729         column_info.insert(cit, ColumnData());
730         row_type const nrows = row_info.size();
731         // set the column values of the column before
732         column_info[c + 1] = column_info[c];
733
734         for (row_type r = 0; r < nrows; ++r) {
735                 cell_info[r].insert(cell_info[r].begin() + c + 1, 
736                         CellData(buffer_));
737 #if 0
738 // FIXME: This code does not work. It deletes the cell's content and
739 // it triggers an assertion if the cursor is at pos > 0.
740                 if (cell_info[r][c].multicolumn == CELL_BEGIN_OF_MULTICOLUMN)
741                         cell_info[r][c + 1].multicolumn = CELL_PART_OF_MULTICOLUMN;
742                 else
743                         cell_info[r][c + 1].multicolumn = cell_info[r][c].multicolumn;
744 #endif
745         }
746         updateIndexes();
747         for (row_type r = 0; r < nrows; ++r) {
748                 // inherit line settings
749                 idx_type const i = cellIndex(r, c + 1);
750                 idx_type const j = cellIndex(r, c);
751                 setBottomLine(i, bottomLine(j));
752                 setTopLine(i, topLine(j));
753                 setLeftLine(i, leftLine(j));
754                 if (rightLine(j) && rightLine(j)) {
755                         setRightLine(i, true);
756                         setRightLine(j, false);
757                 }
758                 //
759                 cellInfo(i).inset->clear();
760                 if (buffer().params().trackChanges)
761                         cellInfo(i).inset->setChange(Change(Change::INSERTED));
762         }
763 }
764
765
766 void Tabular::deleteColumn(col_type const column)
767 {
768         // Not allowed to delete last column
769         if (column_info.size() == 1)
770                 return;
771
772         size_t const row_count = row_info.size();
773         for (row_type i = 0; i < row_count; ++i) {
774                 // Care about multicolumn cells
775                 if (column + 1 < column_info.size() &&
776                     cell_info[i][column].multicolumn == CELL_BEGIN_OF_MULTICOLUMN &&
777                     cell_info[i][column + 1].multicolumn == CELL_PART_OF_MULTICOLUMN) {
778                         cell_info[i][column + 1].multicolumn = CELL_BEGIN_OF_MULTICOLUMN;
779                 }
780                 cell_info[i].erase(cell_info[i].begin() + column);
781         }
782         column_info.erase(column_info.begin() + column);
783         updateIndexes();
784 }
785
786
787 void Tabular::copyColumn(col_type const column)
788 {
789         BufferParams const & bp = buffer().params();
790         column_info.insert(column_info.begin() + column, column_info[column]);
791
792         size_t row_count = row_info.size();
793         for (row_type i = 0; i < row_count; ++i)
794                 cell_info[i].insert(cell_info[i].begin() + column, cell_info[i][column]);
795
796         if (bp.trackChanges)
797                 for (row_type i = 0; i < row_count; ++i)
798                         cell_info[i][column + 1].inset->setChange(Change(Change::INSERTED));
799         updateIndexes();
800 }
801
802
803 void Tabular::updateIndexes()
804 {
805         setBuffer(buffer());
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(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                 // When unsetting a caption row, also all existing
1802                 // captions in this row must be dissolved.
1803         }
1804         row_info[row].caption = what;
1805         return i;
1806 }
1807
1808
1809 bool Tabular::ltCaption(row_type row) const
1810 {
1811         return row_info[row].caption;
1812 }
1813
1814
1815 bool Tabular::haveLTCaption() const
1816 {
1817         for (row_type i = 0; i < row_info.size(); ++i)
1818                 if (row_info[i].caption)
1819                         return true;
1820         return false;
1821 }
1822
1823
1824 // end longtable support functions
1825
1826 void Tabular::setRowAscent(row_type row, int height)
1827 {
1828         if (row >= row_info.size() || row_info[row].ascent == height)
1829                 return;
1830         row_info[row].ascent = height;
1831 }
1832
1833
1834 void Tabular::setRowDescent(row_type row, int height)
1835 {
1836         if (row >= row_info.size() || row_info[row].descent == height)
1837                 return;
1838         row_info[row].descent = height;
1839 }
1840
1841
1842 int Tabular::rowAscent(row_type row) const
1843 {
1844         if (row >= row_info.size())
1845                 return 0;
1846         return row_info[row].ascent;
1847 }
1848
1849
1850 int Tabular::rowDescent(row_type row) const
1851 {
1852         LASSERT(row < row_info.size(), /**/);
1853         return row_info[row].descent;
1854 }
1855
1856
1857 int Tabular::height() const
1858 {
1859         int height = 0;
1860         for (row_type row = 0; row < row_info.size(); ++row)
1861                 height += rowAscent(row) + rowDescent(row) +
1862                         getAdditionalHeight(row);
1863         return height;
1864 }
1865
1866
1867 bool Tabular::isPartOfMultiColumn(row_type row, col_type column) const
1868 {
1869         LASSERT(row < row_info.size(), /**/);
1870         LASSERT(column < column_info.size(), /**/);
1871         return cell_info[row][column].multicolumn == CELL_PART_OF_MULTICOLUMN;
1872 }
1873
1874
1875 int Tabular::TeXTopHLine(odocstream & os, row_type row, string const lang) const
1876 {
1877         // we only output complete row lines and the 1st row here, the rest
1878         // is done in Tabular::TeXBottomHLine(...)
1879
1880         // get for each column the topline (if any)
1881         col_type const ncols = column_info.size();
1882         vector<bool> topline;
1883         col_type nset = 0;
1884         for (col_type c = 0; c < ncols; ++c) {
1885                 topline.push_back(topLine(cellIndex(row, c)));
1886                 if (topline[c])
1887                         ++nset;
1888         }
1889
1890         // do nothing if empty first row, or incomplete row line after
1891         if ((row == 0 && nset == 0) || (row > 0 && nset != ncols))
1892                 return 0;
1893
1894         // only output complete row lines and the 1st row's clines
1895         if (nset == ncols) {
1896                 if (use_booktabs) {
1897                         os << (row == 0 ? "\\toprule " : "\\midrule ");
1898                 } else {
1899                         os << "\\hline ";
1900                 }
1901         } else if (row == 0) {
1902                 for (col_type c = 0; c < ncols; ++c) {
1903                         if (topline[c]) {
1904                                 //babel makes the "-" character an active one, so we have to suppress this here
1905                                 //see http://groups.google.com/group/comp.text.tex/browse_thread/thread/af769424a4a0f289#
1906                                 if (lang == "slovak" || lang == "czech")
1907                                         os << (use_booktabs ? "\\expandafter\\cmidrule\\expandafter{\\expandafter" :
1908                                                               "\\expandafter\\cline\\expandafter{\\expandafter")
1909                                                                                   << c + 1 << "\\string-";
1910                                 else
1911                                         os << (use_booktabs ? "\\cmidrule{" : "\\cline{") << c + 1 << '-';
1912                                 // get to last column of line span
1913                                 while (c < ncols && topline[c])
1914                                         ++c;
1915                                 os << c << "} ";
1916                         }
1917                 }
1918         }
1919         os << "\n";
1920         return 1;
1921 }
1922
1923
1924 int Tabular::TeXBottomHLine(odocstream & os, row_type row, string const lang) const
1925 {
1926         // we output bottomlines of row r and the toplines of row r+1
1927         // if the latter do not span the whole tabular
1928
1929         // get the bottomlines of row r, and toplines in next row
1930         bool lastrow = row == row_info.size() - 1;
1931         col_type const ncols = column_info.size();
1932         vector<bool> bottomline, topline;
1933         bool nextrowset = true;
1934         for (col_type c = 0; c < ncols; ++c) {
1935                 bottomline.push_back(bottomLine(cellIndex(row, c)));
1936                 topline.push_back(!lastrow && topLine(cellIndex(row + 1, c)));
1937                 nextrowset &= topline[c];
1938         }
1939
1940         // combine this row's bottom lines and next row's toplines if necessary
1941         col_type nset = 0;
1942         for (col_type c = 0; c < ncols; ++c) {
1943                 if (!nextrowset)
1944                         bottomline[c] = bottomline[c] || topline[c];
1945                 if (bottomline[c])
1946                         ++nset;
1947         }
1948
1949         // do nothing if empty, OR incomplete row line with a topline in next row
1950         if (nset == 0 || (nextrowset && nset != ncols))
1951                 return 0;
1952
1953         if (nset == ncols) {
1954                 if (use_booktabs)
1955                         os << (lastrow ? "\\bottomrule" : "\\midrule");
1956                 else
1957                         os << "\\hline";
1958         } else {
1959                 for (col_type c = 0; c < ncols; ++c) {
1960                         if (bottomline[c]) {
1961                                 //babel makes the "-" character an active one, so we have to suppress this here
1962                                 //see http://groups.google.com/group/comp.text.tex/browse_thread/thread/af769424a4a0f289#
1963                                 if (lang == "slovak" || lang == "czech")
1964                                         os << (use_booktabs ? "\\expandafter\\cmidrule\\expandafter{\\expandafter" :
1965                                                               "\\expandafter\\cline\\expandafter{\\expandafter")
1966                                                                                   << c + 1 << "\\string-";
1967                                 else
1968                                         os << (use_booktabs ? "\\cmidrule{" : "\\cline{") << c + 1 << '-';
1969                                 // get to last column of line span
1970                                 while (c < ncols && bottomline[c])
1971                                         ++c;
1972                                 os << c << "} ";
1973                         }
1974                 }
1975         }
1976         os << "\n";
1977         return 1;
1978 }
1979
1980
1981 int Tabular::TeXCellPreamble(odocstream & os, idx_type cell, bool & ismulticol) const
1982 {
1983         int ret = 0;
1984         row_type const r = cellRow(cell);
1985         if (is_long_tabular && row_info[r].caption)
1986                 return ret;
1987
1988         Tabular::VAlignment valign =  getVAlignment(cell, !isMultiColumn(cell));
1989         LyXAlignment align = getAlignment(cell, !isMultiColumn(cell));
1990         // figure out how to set the lines
1991         // we always set double lines to the right of the cell
1992         col_type const c = cellColumn(cell);
1993         col_type const nextcol = c + columnSpan(cell);
1994         bool colright = columnRightLine(c);
1995         bool colleft = columnLeftLine(c);
1996         bool nextcolleft = nextcol < column_info.size() && columnLeftLine(nextcol);
1997         bool nextcellleft = nextcol < column_info.size() 
1998                 && leftLine(cellIndex(r, nextcol));
1999         bool coldouble = colright && nextcolleft;
2000         bool celldouble = rightLine(cell) && nextcellleft;
2001         ismulticol = isMultiColumn(cell) 
2002                 || (c == 0 && colleft != leftLine(cell))
2003                 || ((colright || nextcolleft) && !rightLine(cell) && !nextcellleft)
2004                 || (!colright && !nextcolleft && (rightLine(cell) || nextcellleft))
2005                 || (coldouble != celldouble);
2006         if (ismulticol) {
2007                 os << "\\multicolumn{" << columnSpan(cell) << "}{";
2008                 if (c ==0 && leftLine(cell))
2009                         os << '|';
2010                 if (!cellInfo(cell).align_special.empty()) {
2011                         os << cellInfo(cell).align_special;
2012                 } else {
2013                         if (!getPWidth(cell).zero()) {
2014                                 switch (align) {
2015                                 case LYX_ALIGN_LEFT:
2016                                         os << ">{\\raggedright}";
2017                                         break;
2018                                 case LYX_ALIGN_RIGHT:
2019                                         os << ">{\\raggedleft}";
2020                                         break;
2021                                 case LYX_ALIGN_CENTER:
2022                                         os << ">{\\centering}";
2023                                         break;
2024                                 default:
2025                                         break;
2026                                 }
2027                                 switch (valign) {
2028                                 case LYX_VALIGN_TOP:
2029                                         os << 'p';
2030                                         break;
2031                                 case LYX_VALIGN_MIDDLE:
2032                                         os << 'm';
2033                                         break;
2034                                 case LYX_VALIGN_BOTTOM:
2035                                         os << 'b';
2036                                         break;
2037                                 }
2038                                 os << '{'
2039                                    << from_ascii(getPWidth(cell).asLatexString())
2040                                    << '}';
2041                         } else {
2042                                 switch (align) {
2043                                 case LYX_ALIGN_LEFT:
2044                                         os << 'l';
2045                                         break;
2046                                 case LYX_ALIGN_RIGHT:
2047                                         os << 'r';
2048                                         break;
2049                                 default:
2050                                         os << 'c';
2051                                         break;
2052                                 }
2053                         } // end if else !getPWidth
2054                 } // end if else !cellinfo_of_cell
2055                 if (rightLine(cell) || nextcellleft)
2056                         os << '|';
2057                 if (celldouble)
2058                         // add extra vertical line if we want a double one
2059                         os << '|';
2060                 os << "}{";
2061                 }
2062         if (getRotateCell(cell)) {
2063                 os << "\\begin{sideways}\n";
2064                 ++ret;
2065         }
2066         if (getUsebox(cell) == BOX_PARBOX) {
2067                 os << "\\parbox[";
2068                 switch (valign) {
2069                 case LYX_VALIGN_TOP:
2070                         os << 't';
2071                         break;
2072                 case LYX_VALIGN_MIDDLE:
2073                         os << 'c';
2074                         break;
2075                 case LYX_VALIGN_BOTTOM:
2076                         os << 'b';
2077                         break;
2078                 }
2079                 os << "]{" << from_ascii(getPWidth(cell).asLatexString())
2080                    << "}{";
2081         } else if (getUsebox(cell) == BOX_MINIPAGE) {
2082                 os << "\\begin{minipage}[";
2083                 switch (valign) {
2084                 case LYX_VALIGN_TOP:
2085                         os << 't';
2086                         break;
2087                 case LYX_VALIGN_MIDDLE:
2088                         os << 'm';
2089                         break;
2090                 case LYX_VALIGN_BOTTOM:
2091                         os << 'b';
2092                         break;
2093                 }
2094                 os << "]{" << from_ascii(getPWidth(cell).asLatexString())
2095                    << "}\n";
2096                 ++ret;
2097         }
2098         return ret;
2099 }
2100
2101
2102 int Tabular::TeXCellPostamble(odocstream & os, idx_type cell, bool ismulticol) const
2103 {
2104         int ret = 0;
2105         row_type const r = cellRow(cell);
2106         if (is_long_tabular && row_info[r].caption)
2107                 return ret;
2108
2109         // usual cells
2110         if (getUsebox(cell) == BOX_PARBOX)
2111                 os << '}';
2112         else if (getUsebox(cell) == BOX_MINIPAGE) {
2113                 os << "%\n\\end{minipage}";
2114                 ret += 2;
2115         }
2116         if (getRotateCell(cell)) {
2117                 os << "%\n\\end{sideways}";
2118                 ++ret;
2119         }
2120         if (ismulticol) {
2121                 os << '}';
2122         }
2123         return ret;
2124 }
2125
2126
2127 int Tabular::TeXLongtableHeaderFooter(odocstream & os,
2128                                          OutputParams const & runparams) const
2129 {
2130         if (!is_long_tabular)
2131                 return 0;
2132
2133         int ret = 0;
2134         // caption handling
2135         // the caption must be output before the headers
2136         if (haveLTCaption()) {
2137                 for (row_type i = 0; i < row_info.size(); ++i) {
2138                         if (row_info[i].caption) {
2139                                 ret += TeXRow(os, i, runparams);
2140                         }
2141                 }
2142         }
2143         // output first header info
2144         // first header must be output before the header, otherwise the
2145         // correct caption placement becomes really weird
2146         if (haveLTFirstHead()) {
2147                 if (endfirsthead.topDL) {
2148                         os << "\\hline\n";
2149                         ++ret;
2150                 }
2151                 for (row_type i = 0; i < row_info.size(); ++i) {
2152                         if (row_info[i].endfirsthead) {
2153                                 ret += TeXRow(os, i, runparams);
2154                         }
2155                 }
2156                 if (endfirsthead.bottomDL) {
2157                         os << "\\hline\n";
2158                         ++ret;
2159                 }
2160                 os << "\\endfirsthead\n";
2161                 ++ret;
2162         }
2163         // output header info
2164         if (haveLTHead()) {
2165                 if (endfirsthead.empty && !haveLTFirstHead()) {
2166                         os << "\\endfirsthead\n";
2167                         ++ret;
2168                 }
2169                 if (endhead.topDL) {
2170                         os << "\\hline\n";
2171                         ++ret;
2172                 }
2173                 for (row_type i = 0; i < row_info.size(); ++i) {
2174                         if (row_info[i].endhead) {
2175                                 ret += TeXRow(os, i, runparams);
2176                         }
2177                 }
2178                 if (endhead.bottomDL) {
2179                         os << "\\hline\n";
2180                         ++ret;
2181                 }
2182                 os << "\\endhead\n";
2183                 ++ret;
2184         }
2185         // output footer info
2186         if (haveLTFoot()) {
2187                 if (endfoot.topDL) {
2188                         os << "\\hline\n";
2189                         ++ret;
2190                 }
2191                 for (row_type i = 0; i < row_info.size(); ++i) {
2192                         if (row_info[i].endfoot) {
2193                                 ret += TeXRow(os, i, runparams);
2194                         }
2195                 }
2196                 if (endfoot.bottomDL) {
2197                         os << "\\hline\n";
2198                         ++ret;
2199                 }
2200                 os << "\\endfoot\n";
2201                 ++ret;
2202                 if (endlastfoot.empty && !haveLTLastFoot()) {
2203                         os << "\\endlastfoot\n";
2204                         ++ret;
2205                 }
2206         }
2207         // output lastfooter info
2208         if (haveLTLastFoot()) {
2209                 if (endlastfoot.topDL) {
2210                         os << "\\hline\n";
2211                         ++ret;
2212                 }
2213                 for (row_type i = 0; i < row_info.size(); ++i) {
2214                         if (row_info[i].endlastfoot) {
2215                                 ret += TeXRow(os, i, runparams);
2216                         }
2217                 }
2218                 if (endlastfoot.bottomDL) {
2219                         os << "\\hline\n";
2220                         ++ret;
2221                 }
2222                 os << "\\endlastfoot\n";
2223                 ++ret;
2224         }
2225         return ret;
2226 }
2227
2228
2229 bool Tabular::isValidRow(row_type row) const
2230 {
2231         if (!is_long_tabular)
2232                 return true;
2233         return !row_info[row].endhead && !row_info[row].endfirsthead
2234                 && !row_info[row].endfoot && !row_info[row].endlastfoot
2235                 && !row_info[row].caption;
2236 }
2237
2238
2239 int Tabular::TeXRow(odocstream & os, row_type i,
2240                        OutputParams const & runparams) const
2241 {
2242         idx_type cell = cellIndex(i, 0);
2243         shared_ptr<InsetTableCell> inset = cellInset(cell);
2244         Paragraph const & par = inset->paragraphs().front();
2245         string const lang = par.getParLanguage(buffer().params())->lang();
2246
2247         //output the top line
2248         int ret = TeXTopHLine(os, i, lang);
2249
2250         if (row_info[i].top_space_default) {
2251                 if (use_booktabs)
2252                         os << "\\addlinespace\n";
2253                 else
2254                         os << "\\noalign{\\vskip\\doublerulesep}\n";
2255                 ++ret;
2256         } else if(!row_info[i].top_space.zero()) {
2257                 if (use_booktabs)
2258                         os << "\\addlinespace["
2259                            << from_ascii(row_info[i].top_space.asLatexString())
2260                            << "]\n";
2261                 else {
2262                         os << "\\noalign{\\vskip"
2263                            << from_ascii(row_info[i].top_space.asLatexString())
2264                            << "}\n";
2265                 }
2266                 ++ret;
2267         }
2268         bool ismulticol = false;
2269         for (col_type j = 0; j < column_info.size(); ++j) {
2270                 if (isPartOfMultiColumn(i, j))
2271                         continue;
2272                 ret += TeXCellPreamble(os, cell, ismulticol);
2273                 shared_ptr<InsetTableCell> inset = cellInset(cell);
2274
2275                 Paragraph const & par = inset->paragraphs().front();
2276                 bool rtl = par.isRTL(buffer().params())
2277                         && !par.empty()
2278                         && getPWidth(cell).zero();
2279
2280                 if (rtl) {
2281                         string const lang =
2282                                 par.getParLanguage(buffer().params())->lang();
2283                         if (lang == "farsi")
2284                                 os << "\\textFR{";
2285                         else if (lang == "arabic_arabi")
2286                                 os << "\\textAR{";
2287                         // currently, remaning RTL languages are
2288                         // arabic_arabtex and hebrew
2289                         else
2290                                 os << "\\R{";
2291                 }
2292                 // pass to the OutputParams that we are in a cell and
2293                 // which alignment we have set.
2294                 // InsetNewline needs this context information.
2295                 OutputParams newrp(runparams);
2296                 newrp.inTableCell = (getAlignment(cell) == LYX_ALIGN_BLOCK)
2297                                     ? OutputParams::PLAIN
2298                                     : OutputParams::ALIGNED;
2299                 ret += inset->latex(os, newrp);
2300                 runparams.encoding = newrp.encoding;
2301                 if (rtl)
2302                         os << '}';
2303
2304                 ret += TeXCellPostamble(os, cell, ismulticol);
2305                 if (!isLastCellInRow(cell)) { // not last cell in row
2306                         os << " & ";
2307                 }
2308                 ++cell;
2309         }
2310         if (row_info[i].caption && !endfirsthead.empty && !haveLTFirstHead())
2311                 // if no first header and no empty first header is used,
2312                 // the caption needs to be terminated by \endfirsthead
2313                 // (bug 6057)
2314                 os << "\\endfirsthead";
2315         else
2316                 os << "\\tabularnewline";
2317         if (row_info[i].bottom_space_default) {
2318                 if (use_booktabs)
2319                         os << "\\addlinespace";
2320                 else
2321                         os << "[\\doublerulesep]";
2322         } else if (!row_info[i].bottom_space.zero()) {
2323                 if (use_booktabs)
2324                         os << "\\addlinespace";
2325                 os << '['
2326                    << from_ascii(row_info[i].bottom_space.asLatexString())
2327                    << ']';
2328         }
2329         os << '\n';
2330         ++ret;
2331
2332         //output the bottom line
2333         ret += TeXBottomHLine(os, i, lang);
2334
2335         if (row_info[i].interline_space_default) {
2336                 if (use_booktabs)
2337                         os << "\\addlinespace\n";
2338                 else
2339                         os << "\\noalign{\\vskip\\doublerulesep}\n";
2340                 ++ret;
2341         } else if (!row_info[i].interline_space.zero()) {
2342                 if (use_booktabs)
2343                         os << "\\addlinespace["
2344                            << from_ascii(row_info[i].interline_space.asLatexString())
2345                            << "]\n";
2346                 else
2347                         os << "\\noalign{\\vskip"
2348                            << from_ascii(row_info[i].interline_space.asLatexString())
2349                            << "}\n";
2350                 ++ret;
2351         }
2352         return ret;
2353 }
2354
2355
2356 int Tabular::latex(odocstream & os, OutputParams const & runparams) const
2357 {
2358         int ret = 0;
2359
2360         //+---------------------------------------------------------------------
2361         //+                      first the opening preamble                    +
2362         //+---------------------------------------------------------------------
2363
2364         if (rotate) {
2365                 os << "\\begin{sideways}\n";
2366                 ++ret;
2367         }
2368         if (is_long_tabular) {
2369                 os << "\\begin{longtable}";
2370                 switch (longtabular_alignment) {
2371                 case LYX_LONGTABULAR_ALIGN_LEFT:
2372                         os << "[l]";
2373                         break;
2374                 case LYX_LONGTABULAR_ALIGN_CENTER:
2375                         break;
2376                 case LYX_LONGTABULAR_ALIGN_RIGHT:
2377                         os << "[r]";
2378                         break;
2379                 }
2380         } else {
2381                 os << "\\begin{tabular}";
2382                 switch (tabular_valignment) {
2383                 case LYX_VALIGN_TOP:
2384                         os << "[t]";
2385                         break;
2386                 case LYX_VALIGN_MIDDLE:
2387                         break;
2388                 case LYX_VALIGN_BOTTOM:
2389                         os << "[b]";
2390                         break;
2391                 }
2392         }
2393         
2394         os << "{";
2395
2396         for (col_type i = 0; i < column_info.size(); ++i) {
2397                 if (columnLeftLine(i))
2398                         os << '|';
2399                 if (!column_info[i].align_special.empty()) {
2400                         os << column_info[i].align_special;
2401                 } else {
2402                         if (!column_info[i].p_width.zero()) {
2403                                 switch (column_info[i].alignment) {
2404                                 case LYX_ALIGN_LEFT:
2405                                         os << ">{\\raggedright}";
2406                                         break;
2407                                 case LYX_ALIGN_RIGHT:
2408                                         os << ">{\\raggedleft}";
2409                                         break;
2410                                 case LYX_ALIGN_CENTER:
2411                                         os << ">{\\centering}";
2412                                         break;
2413                                 case LYX_ALIGN_NONE:
2414                                 case LYX_ALIGN_BLOCK:
2415                                 case LYX_ALIGN_LAYOUT:
2416                                 case LYX_ALIGN_SPECIAL:
2417                                         break;
2418                                 }
2419
2420                                 switch (column_info[i].valignment) {
2421                                 case LYX_VALIGN_TOP:
2422                                         os << 'p';
2423                                         break;
2424                                 case LYX_VALIGN_MIDDLE:
2425                                         os << 'm';
2426                                         break;
2427                                 case LYX_VALIGN_BOTTOM:
2428                                         os << 'b';
2429                                         break;
2430                         }
2431                                 os << '{'
2432                                    << from_ascii(column_info[i].p_width.asLatexString())
2433                                    << '}';
2434                         } else {
2435                                 switch (column_info[i].alignment) {
2436                                 case LYX_ALIGN_LEFT:
2437                                         os << 'l';
2438                                         break;
2439                                 case LYX_ALIGN_RIGHT:
2440                                         os << 'r';
2441                                         break;
2442                                 default:
2443                                         os << 'c';
2444                                         break;
2445                                 }
2446                         } // end if else !column_info[i].p_width
2447                 } // end if else !column_info[i].align_special
2448                 if (columnRightLine(i))
2449                         os << '|';
2450         }
2451         os << "}\n";
2452         ++ret;
2453
2454         ret += TeXLongtableHeaderFooter(os, runparams);
2455
2456         //+---------------------------------------------------------------------
2457         //+                      the single row and columns (cells)            +
2458         //+---------------------------------------------------------------------
2459
2460         for (row_type i = 0; i < row_info.size(); ++i) {
2461                 if (isValidRow(i)) {
2462                         ret += TeXRow(os, i, runparams);
2463                         if (is_long_tabular && row_info[i].newpage) {
2464                                 os << "\\newpage\n";
2465                                 ++ret;
2466                         }
2467                 }
2468         }
2469
2470         //+---------------------------------------------------------------------
2471         //+                      the closing of the tabular                    +
2472         //+---------------------------------------------------------------------
2473
2474         if (is_long_tabular)
2475                 os << "\\end{longtable}";
2476         else
2477                 os << "\\end{tabular}";
2478         if (rotate) {
2479                 os << "\n\\end{sideways}";
2480                 ++ret;
2481         }
2482
2483         return ret;
2484 }
2485
2486
2487 int Tabular::docbookRow(odocstream & os, row_type row,
2488                            OutputParams const & runparams) const
2489 {
2490         int ret = 0;
2491         idx_type cell = getFirstCellInRow(row);
2492
2493         os << "<row>\n";
2494         for (col_type j = 0; j < column_info.size(); ++j) {
2495                 if (isPartOfMultiColumn(row, j))
2496                         continue;
2497
2498                 os << "<entry align=\"";
2499                 switch (getAlignment(cell)) {
2500                 case LYX_ALIGN_LEFT:
2501                         os << "left";
2502                         break;
2503                 case LYX_ALIGN_RIGHT:
2504                         os << "right";
2505                         break;
2506                 default:
2507                         os << "center";
2508                         break;
2509                 }
2510
2511                 os << "\" valign=\"";
2512                 switch (getVAlignment(cell)) {
2513                 case LYX_VALIGN_TOP:
2514                         os << "top";
2515                         break;
2516                 case LYX_VALIGN_BOTTOM:
2517                         os << "bottom";
2518                         break;
2519                 case LYX_VALIGN_MIDDLE:
2520                         os << "middle";
2521                 }
2522                 os << '"';
2523
2524                 if (isMultiColumn(cell)) {
2525                         os << " namest=\"col" << j << "\" ";
2526                         os << "nameend=\"col" << j + columnSpan(cell) - 1<< '"';
2527                 }
2528
2529                 os << '>';
2530                 ret += cellInset(cell)->docbook(os, runparams);
2531                 os << "</entry>\n";
2532                 ++cell;
2533         }
2534         os << "</row>\n";
2535         return ret;
2536 }
2537
2538
2539 int Tabular::docbook(odocstream & os, OutputParams const & runparams) const
2540 {
2541         int ret = 0;
2542
2543         //+---------------------------------------------------------------------
2544         //+                      first the opening preamble                    +
2545         //+---------------------------------------------------------------------
2546
2547         os << "<tgroup cols=\"" << column_info.size()
2548            << "\" colsep=\"1\" rowsep=\"1\">\n";
2549
2550         for (col_type i = 0; i < column_info.size(); ++i) {
2551                 os << "<colspec colname=\"col" << i << "\" align=\"";
2552                 switch (column_info[i].alignment) {
2553                 case LYX_ALIGN_LEFT:
2554                         os << "left";
2555                         break;
2556                 case LYX_ALIGN_RIGHT:
2557                         os << "right";
2558                         break;
2559                 default:
2560                         os << "center";
2561                         break;
2562                 }
2563                 os << '"';
2564                 if (runparams.flavor == OutputParams::XML)
2565                         os << '/';
2566                 os << ">\n";
2567                 ++ret;
2568         }
2569
2570         //+---------------------------------------------------------------------
2571         //+                      Long Tabular case                             +
2572         //+---------------------------------------------------------------------
2573
2574         // output caption info
2575         if (haveLTCaption()) {
2576                 os << "<caption>\n";
2577                 ++ret;
2578                 for (row_type i = 0; i < row_info.size(); ++i) {
2579                         if (row_info[i].caption) {
2580                                 ret += docbookRow(os, i, runparams);
2581                         }
2582                 }
2583                 os << "</caption>\n";
2584                 ++ret;
2585         }
2586         // output header info
2587         if (haveLTHead() || haveLTFirstHead()) {
2588                 os << "<thead>\n";
2589                 ++ret;
2590                 for (row_type i = 0; i < row_info.size(); ++i) {
2591                         if (row_info[i].endhead || row_info[i].endfirsthead) {
2592                                 ret += docbookRow(os, i, runparams);
2593                         }
2594                 }
2595                 os << "</thead>\n";
2596                 ++ret;
2597         }
2598         // output footer info
2599         if (haveLTFoot() || haveLTLastFoot()) {
2600                 os << "<tfoot>\n";
2601                 ++ret;
2602                 for (row_type i = 0; i < row_info.size(); ++i) {
2603                         if (row_info[i].endfoot || row_info[i].endlastfoot) {
2604                                 ret += docbookRow(os, i, runparams);
2605                         }
2606                 }
2607                 os << "</tfoot>\n";
2608                 ++ret;
2609         }
2610
2611         //+---------------------------------------------------------------------
2612         //+                      the single row and columns (cells)            +
2613         //+---------------------------------------------------------------------
2614
2615         os << "<tbody>\n";
2616         ++ret;
2617         for (row_type i = 0; i < row_info.size(); ++i) {
2618                 if (isValidRow(i)) {
2619                         ret += docbookRow(os, i, runparams);
2620                 }
2621         }
2622         os << "</tbody>\n";
2623         ++ret;
2624         //+---------------------------------------------------------------------
2625         //+                      the closing of the tabular                    +
2626         //+---------------------------------------------------------------------
2627
2628         os << "</tgroup>";
2629         ++ret;
2630
2631         return ret;
2632 }
2633
2634
2635 bool Tabular::plaintextTopHLine(odocstream & os, row_type row,
2636                                    vector<unsigned int> const & clen) const
2637 {
2638         idx_type const fcell = getFirstCellInRow(row);
2639         idx_type const n = numberOfCellsInRow(fcell) + fcell;
2640         idx_type tmp = 0;
2641
2642         for (idx_type i = fcell; i < n; ++i) {
2643                 if (topLine(i)) {
2644                         ++tmp;
2645                         break;
2646                 }
2647         }
2648         if (!tmp)
2649                 return false;
2650
2651         char_type ch;
2652         for (idx_type i = fcell; i < n; ++i) {
2653                 if (topLine(i)) {
2654                         if (leftLine(i))
2655                                 os << "+-";
2656                         else
2657                                 os << "--";
2658                         ch = '-';
2659                 } else {
2660                         os << "  ";
2661                         ch = ' ';
2662                 }
2663                 col_type column = cellColumn(i);
2664                 int len = clen[column];
2665                 while (column < column_info.size() - 1
2666                        && isPartOfMultiColumn(row, ++column))
2667                         len += clen[column] + 4;
2668                 os << docstring(len, ch);
2669                 if (topLine(i)) {
2670                         if (rightLine(i))
2671                                 os << "-+";
2672                         else
2673                                 os << "--";
2674                 } else {
2675                         os << "  ";
2676                 }
2677         }
2678         os << endl;
2679         return true;
2680 }
2681
2682
2683 bool Tabular::plaintextBottomHLine(odocstream & os, row_type row,
2684                                       vector<unsigned int> const & clen) const
2685 {
2686         idx_type const fcell = getFirstCellInRow(row);
2687         idx_type const n = numberOfCellsInRow(fcell) + fcell;
2688         idx_type tmp = 0;
2689
2690         for (idx_type i = fcell; i < n; ++i) {
2691                 if (bottomLine(i)) {
2692                         ++tmp;
2693                         break;
2694                 }
2695         }
2696         if (!tmp)
2697                 return false;
2698
2699         char_type ch;
2700         for (idx_type i = fcell; i < n; ++i) {
2701                 if (bottomLine(i)) {
2702                         if (leftLine(i))
2703                                 os << "+-";
2704                         else
2705                                 os << "--";
2706                         ch = '-';
2707                 } else {
2708                         os << "  ";
2709                         ch = ' ';
2710                 }
2711                 col_type column = cellColumn(i);
2712                 int len = clen[column];
2713                 while (column < column_info.size() -1
2714                        && isPartOfMultiColumn(row, ++column))
2715                         len += clen[column] + 4;
2716                 os << docstring(len, ch);
2717                 if (bottomLine(i)) {
2718                         if (rightLine(i))
2719                                 os << "-+";
2720                         else
2721                                 os << "--";
2722                 } else {
2723                         os << "  ";
2724                 }
2725         }
2726         os << endl;
2727         return true;
2728 }
2729
2730
2731 void Tabular::plaintextPrintCell(odocstream & os,
2732                                OutputParams const & runparams,
2733                                idx_type cell, row_type row, col_type column,
2734                                vector<unsigned int> const & clen,
2735                                bool onlydata) const
2736 {
2737         odocstringstream sstr;
2738         cellInset(cell)->plaintext(sstr, runparams);
2739
2740         if (onlydata) {
2741                 os << sstr.str();
2742                 return;
2743         }
2744
2745         if (leftLine(cell))
2746                 os << "| ";
2747         else
2748                 os << "  ";
2749
2750         unsigned int len1 = sstr.str().length();
2751         unsigned int len2 = clen[column];
2752         while (column < column_info.size() -1
2753                && isPartOfMultiColumn(row, ++column))
2754                 len2 += clen[column] + 4;
2755         len2 -= len1;
2756
2757         switch (getAlignment(cell)) {
2758         default:
2759         case LYX_ALIGN_LEFT:
2760                 len1 = 0;
2761                 break;
2762         case LYX_ALIGN_RIGHT:
2763                 len1 = len2;
2764                 len2 = 0;
2765                 break;
2766         case LYX_ALIGN_CENTER:
2767                 len1 = len2 / 2;
2768                 len2 -= len1;
2769                 break;
2770         }
2771
2772         os << docstring(len1, ' ') << sstr.str()
2773            << docstring(len2, ' ');
2774
2775         if (rightLine(cell))
2776                 os << " |";
2777         else
2778                 os << "  ";
2779 }
2780
2781
2782 void Tabular::plaintext(odocstream & os,
2783                            OutputParams const & runparams, int const depth,
2784                            bool onlydata, char_type delim) const
2785 {
2786         // first calculate the width of the single columns
2787         vector<unsigned int> clen(column_info.size());
2788
2789         if (!onlydata) {
2790                 // first all non (real) multicolumn cells!
2791                 for (col_type j = 0; j < column_info.size(); ++j) {
2792                         clen[j] = 0;
2793                         for (row_type i = 0; i < row_info.size(); ++i) {
2794                                 idx_type cell = cellIndex(i, j);
2795                                 if (isMultiColumnReal(cell))
2796                                         continue;
2797                                 odocstringstream sstr;
2798                                 cellInset(cell)->plaintext(sstr, runparams);
2799                                 if (clen[j] < sstr.str().length())
2800                                         clen[j] = sstr.str().length();
2801                         }
2802                 }
2803                 // then all (real) multicolumn cells!
2804                 for (col_type j = 0; j < column_info.size(); ++j) {
2805                         for (row_type i = 0; i < row_info.size(); ++i) {
2806                                 idx_type cell = cellIndex(i, j);
2807                                 if (!isMultiColumnReal(cell) || isPartOfMultiColumn(i, j))
2808                                         continue;
2809                                 odocstringstream sstr;
2810                                 cellInset(cell)->plaintext(sstr, runparams);
2811                                 int len = int(sstr.str().length());
2812                                 idx_type const n = columnSpan(cell);
2813                                 for (col_type k = j; len > 0 && k < j + n - 1; ++k)
2814                                         len -= clen[k];
2815                                 if (len > int(clen[j + n - 1]))
2816                                         clen[j + n - 1] = len;
2817                         }
2818                 }
2819         }
2820         idx_type cell = 0;
2821         for (row_type i = 0; i < row_info.size(); ++i) {
2822                 if (!onlydata && plaintextTopHLine(os, i, clen))
2823                         os << docstring(depth * 2, ' ');
2824                 for (col_type j = 0; j < column_info.size(); ++j) {
2825                         if (isPartOfMultiColumn(i, j))
2826                                 continue;
2827                         if (onlydata && j > 0)
2828                                 // we don't use operator<< for single UCS4 character.
2829                                 // see explanation in docstream.h
2830                                 os.put(delim);
2831                         plaintextPrintCell(os, runparams, cell, i, j, clen, onlydata);
2832                         ++cell;
2833                 }
2834                 os << endl;
2835                 if (!onlydata) {
2836                         os << docstring(depth * 2, ' ');
2837                         if (plaintextBottomHLine(os, i, clen))
2838                                 os << docstring(depth * 2, ' ');
2839                 }
2840         }
2841 }
2842
2843
2844 shared_ptr<InsetTableCell> Tabular::cellInset(idx_type cell) const
2845 {
2846         return cell_info[cellRow(cell)][cellColumn(cell)].inset;
2847 }
2848
2849
2850 shared_ptr<InsetTableCell> Tabular::cellInset(row_type row,
2851                                                col_type column) const
2852 {
2853         return cell_info[row][column].inset;
2854 }
2855
2856
2857 void Tabular::setCellInset(row_type row, col_type column,
2858                               shared_ptr<InsetTableCell> ins) const
2859 {
2860         CellData & cd = cell_info[row][column];
2861         cd.inset = ins;
2862 }
2863
2864
2865 void Tabular::validate(LaTeXFeatures & features) const
2866 {
2867         features.require("NeedTabularnewline");
2868         if (use_booktabs)
2869                 features.require("booktabs");
2870         if (is_long_tabular)
2871                 features.require("longtable");
2872         if (needRotating())
2873                 features.require("rotating");
2874         for (idx_type cell = 0; cell < numberofcells; ++cell) {
2875                 if (getVAlignment(cell) != LYX_VALIGN_TOP
2876                     || !getPWidth(cell).zero())
2877                         features.require("array");
2878                 cellInset(cell)->validate(features);
2879         }
2880 }
2881
2882
2883 Tabular::BoxType Tabular::useParbox(idx_type cell) const
2884 {
2885         ParagraphList const & parlist = cellInset(cell)->paragraphs();
2886         ParagraphList::const_iterator cit = parlist.begin();
2887         ParagraphList::const_iterator end = parlist.end();
2888
2889         for (; cit != end; ++cit)
2890                 for (int i = 0; i < cit->size(); ++i)
2891                         if (cit->isNewline(i))
2892                                 return BOX_PARBOX;
2893
2894         return BOX_NONE;
2895 }
2896
2897
2898 /////////////////////////////////////////////////////////////////////
2899 //
2900 // InsetTableCell
2901 //
2902 /////////////////////////////////////////////////////////////////////
2903
2904 InsetTableCell::InsetTableCell(Buffer * buf)
2905         : InsetText(buf, InsetText::PlainLayout), isFixedWidth(false),
2906           contentAlign(LYX_ALIGN_CENTER)
2907 {}
2908
2909
2910 bool InsetTableCell::forcePlainLayout(idx_type) const
2911 {
2912         return !isFixedWidth;
2913 }
2914
2915
2916 bool InsetTableCell::allowParagraphCustomization(idx_type) const
2917 {
2918         return isFixedWidth;
2919 }
2920
2921
2922 bool InsetTableCell::getStatus(Cursor & cur, FuncRequest const & cmd,
2923         FuncStatus & status) const
2924 {
2925         bool enabled;
2926         switch (cmd.action) {
2927         case LFUN_LAYOUT:
2928                 enabled = !forcePlainLayout();
2929                 break;
2930         case LFUN_LAYOUT_PARAGRAPH:
2931                 enabled = allowParagraphCustomization();
2932                 break;
2933         default:
2934                 return InsetText::getStatus(cur, cmd, status);
2935         }
2936         status.setEnabled(enabled);
2937         return true;
2938 }
2939
2940 docstring InsetTableCell::asString(bool intoInsets) 
2941 {
2942         docstring retval;
2943         if (paragraphs().empty())
2944                 return retval;
2945         ParagraphList::const_iterator it = paragraphs().begin();
2946         ParagraphList::const_iterator en = paragraphs().end();
2947         bool first = true;
2948         for (; it != en; ++it) {
2949                 if (!first)
2950                         retval += "\n";
2951                 else
2952                         first = false;
2953                 retval += it->asString(intoInsets ? AS_STR_INSETS : AS_STR_NONE);
2954         }
2955         return retval;
2956 }
2957
2958
2959
2960 /////////////////////////////////////////////////////////////////////
2961 //
2962 // InsetTabular
2963 //
2964 /////////////////////////////////////////////////////////////////////
2965
2966 InsetTabular::InsetTabular(Buffer * buf, row_type rows,
2967                            col_type columns)
2968         : Inset(buf), tabular(buf, max(rows, row_type(1)), max(columns, col_type(1))), scx_(0), 
2969         rowselect_(false), colselect_(false)
2970 {
2971 }
2972
2973
2974 InsetTabular::InsetTabular(InsetTabular const & tab)
2975         : Inset(tab), tabular(tab.tabular),  scx_(0)
2976 {
2977 }
2978
2979
2980 InsetTabular::~InsetTabular()
2981 {
2982         hideDialogs("tabular", this);
2983 }
2984
2985
2986 void InsetTabular::setBuffer(Buffer & buf)
2987 {
2988         tabular.setBuffer(buf);
2989         Inset::setBuffer(buf);
2990 }
2991
2992
2993 bool InsetTabular::insetAllowed(InsetCode code) const
2994 {
2995         if (code == MATHMACRO_CODE
2996                 || (code == CAPTION_CODE && !tabular.is_long_tabular))
2997                 return false;
2998
2999         return true;
3000 }
3001
3002
3003 void InsetTabular::write(ostream & os) const
3004 {
3005         os << "Tabular" << endl;
3006         tabular.write(os);
3007 }
3008
3009
3010 docstring InsetTabular::contextMenu(BufferView const &, int, int) const
3011 {
3012         // FIXME: depending on the selection state, we could offer a different menu.
3013         return from_ascii("context-tabular");
3014 }
3015
3016
3017 void InsetTabular::read(Lexer & lex)
3018 {
3019         //bool const old_format = (lex.getString() == "\\LyXTable");
3020
3021         tabular.read(lex);
3022
3023         //if (old_format)
3024         //      return;
3025
3026         lex.next();
3027         string token = lex.getString();
3028         while (lex && token != "\\end_inset") {
3029                 lex.next();
3030                 token = lex.getString();
3031         }
3032         if (!lex)
3033                 lex.printError("Missing \\end_inset at this point. ");
3034 }
3035
3036
3037 int InsetTabular::rowFromY(Cursor & cur, int y) const
3038 {
3039         // top y coordinate of tabular
3040         int h = yo(cur.bv()) - tabular.rowAscent(0);
3041         size_t nrows = tabular.row_info.size();
3042         row_type r = 0;
3043         for (; r < nrows && y > h; ++r) {
3044                 h += tabular.rowAscent(r);
3045                 h += tabular.rowDescent(r);
3046                 h += tabular.getAdditionalHeight(r);
3047         }
3048         return r - 1;
3049 }
3050
3051
3052 int InsetTabular::columnFromX(Cursor & cur, int x) const
3053 {
3054         // left x coordinate of tabular
3055         int w = xo(cur.bv()) + ADD_TO_TABULAR_WIDTH;
3056         size_t ncols = tabular.column_info.size();
3057         col_type c = 0;
3058         for (; c < ncols && x > w; ++c)
3059                 w += tabular.columnWidth(c);
3060         return c - 1;
3061 }
3062
3063
3064 void InsetTabular::metrics(MetricsInfo & mi, Dimension & dim) const
3065 {
3066         //lyxerr << "InsetTabular::metrics: " << mi.base.bv << " width: " <<
3067         //      mi.base.textwidth << "\n";
3068         if (!mi.base.bv) {
3069                 LYXERR0("need bv");
3070                 LASSERT(false, /**/);
3071         }
3072
3073         row_type i = 0;
3074         for (idx_type cell = 0; i < tabular.row_info.size(); ++i) {
3075                 int maxAsc = 0;
3076                 int maxDesc = 0;
3077                 for (col_type j = 0; j < tabular.column_info.size(); ++j) {
3078                         if (tabular.isPartOfMultiColumn(i, j))
3079                                 // Multicolumn cell, but not first one
3080                                 continue;
3081                         Dimension dim;
3082                         MetricsInfo m = mi;
3083                         Length p_width;
3084                         if (tabular.cell_info[i][j].multicolumn ==
3085                                 Tabular::CELL_BEGIN_OF_MULTICOLUMN)
3086                                 p_width = tabular.cellInfo(cell).p_width;
3087                         else
3088                                 p_width = tabular.column_info[j].p_width;
3089                         if (!p_width.zero())
3090                                 m.base.textwidth = p_width.inPixels(mi.base.textwidth);
3091                         tabular.cellInset(cell)->metrics(m, dim);
3092                         if (!p_width.zero())
3093                                 dim.wid = m.base.textwidth;
3094                         tabular.setCellWidth(cell, dim.wid);
3095                         maxAsc  = max(maxAsc, dim.asc);
3096                         maxDesc = max(maxDesc, dim.des);
3097                         ++cell;
3098                 }
3099                 int const top_space = tabular.row_info[i].top_space_default ?
3100                         default_line_space :
3101                         tabular.row_info[i].top_space.inPixels(mi.base.textwidth);
3102                 tabular.setRowAscent(i, maxAsc + ADD_TO_HEIGHT + top_space);
3103                 int const bottom_space = tabular.row_info[i].bottom_space_default ?
3104                         default_line_space :
3105                         tabular.row_info[i].bottom_space.inPixels(mi.base.textwidth);
3106                 tabular.setRowDescent(i, maxDesc + ADD_TO_HEIGHT + bottom_space);
3107         }
3108         tabular.updateColumnWidths();
3109         dim.asc = tabular.rowAscent(0);
3110         dim.des = tabular.height() - dim.asc;
3111         dim.wid = tabular.width() + 2 * ADD_TO_TABULAR_WIDTH;
3112 }
3113
3114 bool InsetTabular::isCellSelected(Cursor & cur, row_type row, col_type col) 
3115         const
3116 {
3117         if (&cur.inset() == this && cur.selection()) {
3118                 if (cur.selIsMultiCell()) {
3119                         row_type rs, re;
3120                         col_type cs, ce;
3121                         getSelection(cur, rs, re, cs, ce);
3122                         
3123                         if (col >= cs && col <= ce && row >= rs && row <= re)
3124                                 return true;
3125                 } else 
3126                         if (col == tabular.cellColumn(cur.idx()) 
3127                                 && row == tabular.cellRow(cur.idx())) {
3128                         CursorSlice const & beg = cur.selBegin();
3129                         CursorSlice const & end = cur.selEnd();
3130
3131                         if ((end.lastpos() > 0 || end.lastpit() > 0)
3132                                   && end.pos() == end.lastpos() && beg.pos() == 0
3133                                   && end.pit() == end.lastpit() && beg.pit() == 0)
3134                                 return true;
3135                 }
3136         }
3137         return false;
3138 }
3139
3140
3141 void InsetTabular::draw(PainterInfo & pi, int x, int y) const
3142 {
3143         //lyxerr << "InsetTabular::draw: " << x << " " << y << endl;
3144         BufferView * bv = pi.base.bv;
3145         Cursor & cur = pi.base.bv->cursor();
3146
3147         // FIXME: As the full background is painted in drawSelection(),
3148         // we have no choice but to do a full repaint for the Text cells.
3149         pi.full_repaint = true;
3150
3151         resetPos(bv->cursor());
3152
3153         x += scx_;
3154         x += ADD_TO_TABULAR_WIDTH;
3155
3156         bool const original_drawing_state = pi.pain.isDrawingEnabled();
3157         bool const original_selection_state = pi.selected;
3158
3159         idx_type idx = 0;
3160         first_visible_cell = Tabular::npos;
3161         for (row_type i = 0; i < tabular.row_info.size(); ++i) {
3162                 int nx = x;
3163                 int const a = tabular.rowAscent(i);
3164                 int const d = tabular.rowDescent(i);
3165                 idx = tabular.cellIndex(i, 0);
3166                 for (col_type j = 0; j < tabular.column_info.size(); ++j) {
3167                         if (tabular.isPartOfMultiColumn(i, j))
3168                                 continue;
3169                         if (first_visible_cell == Tabular::npos)
3170                                 first_visible_cell = idx;
3171
3172                         pi.selected |= isCellSelected(cur, i, j);
3173                         int const cx = nx + tabular.getBeginningOfTextInCell(idx);
3174                         // Cache the Inset position.
3175                         bv->coordCache().insets().add(cell(idx).get(), cx, y);
3176                         if (nx + tabular.columnWidth(idx) < 0
3177                             || nx > bv->workWidth()
3178                             || y + d < 0
3179                             || y - a > bv->workHeight()) {
3180                                 pi.pain.setDrawingEnabled(false);
3181                                 cell(idx)->draw(pi, cx, y);
3182                                 drawCellLines(pi.pain, nx, y, i, idx, pi.change_);
3183                                 pi.pain.setDrawingEnabled(original_drawing_state);
3184                         } else {
3185                                 cell(idx)->draw(pi, cx, y);
3186                                 drawCellLines(pi.pain, nx, y, i, idx, pi.change_);
3187                         }
3188                         nx += tabular.columnWidth(idx);
3189                         ++idx;
3190                         pi.selected = original_selection_state;
3191                 }
3192
3193                 if (i + 1 < tabular.row_info.size())
3194                         y += d + tabular.rowAscent(i + 1) +
3195                                 tabular.getAdditionalHeight(i + 1);
3196         }
3197 }
3198
3199
3200 void InsetTabular::drawSelection(PainterInfo & pi, int x, int y) const
3201 {
3202         Cursor & cur = pi.base.bv->cursor();
3203         resetPos(cur);
3204
3205         x += scx_ + ADD_TO_TABULAR_WIDTH;
3206
3207         // FIXME: it is wrong to completely paint the background
3208         // if we want to do single row painting.
3209
3210         // Paint background of current tabular
3211         int const w = tabular.width();
3212         int const h = tabular.height();
3213         int yy = y - tabular.rowAscent(0);
3214         pi.pain.fillRectangle(x, yy, w, h, pi.backgroundColor(this));
3215
3216         if (!cur.selection())
3217                 return;
3218         if (&cur.inset() != this)
3219                 return;
3220
3221         //resetPos(cur);
3222
3223         bool const full_cell_selected = isCellSelected(cur,
3224                 tabular.cellRow(cur.idx()), tabular.cellColumn(cur.idx()));
3225
3226         if (cur.selIsMultiCell() || full_cell_selected) {
3227                 y -= tabular.rowAscent(0);
3228                 for (row_type j = 0; j < tabular.row_info.size(); ++j) {
3229                         int const a = tabular.rowAscent(j);
3230                         int const h = a + tabular.rowDescent(j);
3231                         int xx = x;
3232                         y += tabular.getAdditionalHeight(j);
3233                         for (col_type i = 0; i < tabular.column_info.size(); ++i) {
3234                                 if (tabular.isPartOfMultiColumn(j, i))
3235                                         continue;
3236                                 idx_type const cell =
3237                                         tabular.cellIndex(j, i);
3238                                 int const w = tabular.columnWidth(cell);
3239                                 if (isCellSelected(cur, j, i))
3240                                         pi.pain.fillRectangle(xx, y, w, h, Color_selection);
3241                                 xx += w;
3242                         }
3243                         y += h;
3244                 }
3245
3246         } else {
3247                 x += cellXPos(cur.idx());
3248                 x += tabular.getBeginningOfTextInCell(cur.idx());
3249                 cell(cur.idx())->drawSelection(pi, x, 0 /* ignored */);
3250         }
3251 }
3252
3253
3254 void InsetTabular::drawCellLines(Painter & pain, int x, int y,
3255                                  row_type row, idx_type cell, Change const & change) const
3256 {
3257         int x2 = x + tabular.columnWidth(cell);
3258         bool on_off = false;
3259         Color col = Color_tabularline;
3260         Color onoffcol = Color_tabularonoffline;
3261
3262         if (change.changed()) {
3263                 col = change.color();
3264                 onoffcol = change.color();
3265         }
3266
3267         if (!tabular.topAlreadyDrawn(cell)) {
3268                 on_off = !tabular.topLine(cell);
3269                 pain.line(x, y - tabular.rowAscent(row),
3270                           x2, y -  tabular.rowAscent(row),
3271                           on_off ? onoffcol : col,
3272                           on_off ? Painter::line_onoffdash : Painter::line_solid);
3273         }
3274         on_off = !tabular.bottomLine(cell);
3275         pain.line(x, y + tabular.rowDescent(row),
3276                   x2, y + tabular.rowDescent(row),
3277                   on_off ? onoffcol : col,
3278                   on_off ? Painter::line_onoffdash : Painter::line_solid);
3279         if (!tabular.leftAlreadyDrawn(cell)) {
3280                 on_off = !tabular.leftLine(cell);
3281                 pain.line(x, y -  tabular.rowAscent(row),
3282                           x, y +  tabular.rowDescent(row),
3283                           on_off ? onoffcol : col,
3284                           on_off ? Painter::line_onoffdash : Painter::line_solid);
3285         }
3286         on_off = !tabular.rightLine(cell);
3287         pain.line(x2 - tabular.getAdditionalWidth(cell),
3288                   y -  tabular.rowAscent(row),
3289                   x2 - tabular.getAdditionalWidth(cell),
3290                   y +  tabular.rowDescent(row),
3291                   on_off ? onoffcol : col,
3292                   on_off ? Painter::line_onoffdash : Painter::line_solid);
3293 }
3294
3295
3296 void InsetTabular::edit(Cursor & cur, bool front, EntryDirection)
3297 {
3298         //lyxerr << "InsetTabular::edit: " << this << endl;
3299         cur.finishUndo();
3300         cur.setSelection(false);
3301         cur.push(*this);
3302         if (front) {
3303                 if (isRightToLeft(cur))
3304                         cur.idx() = tabular.getLastCellInRow(0);
3305                 else
3306                         cur.idx() = 0;
3307                 cur.pit() = 0;
3308                 cur.pos() = 0;
3309         } else {
3310                 if (isRightToLeft(cur))
3311                         cur.idx() = tabular.getFirstCellInRow(tabular.row_info.size() - 1);
3312                 else
3313                         cur.idx() = tabular.numberofcells - 1;
3314                 cur.pit() = 0;
3315                 cur.pos() = cur.lastpos(); // FIXME crude guess
3316         }
3317         // FIXME: this accesses the position cache before it is initialized
3318         //resetPos(cur);
3319         //cur.bv().fitCursor();
3320 }
3321
3322
3323 void InsetTabular::updateLabels(ParIterator const & it)
3324 {
3325         // In a longtable, tell captions what the current float is
3326         Counters & cnts = buffer().masterBuffer()->params().documentClass().counters();
3327         string const saveflt = cnts.current_float();
3328         if (tabular.is_long_tabular)
3329                 cnts.current_float("table");
3330
3331         ParIterator it2 = it;
3332         it2.forwardPos();
3333         size_t const end = it2.nargs();
3334         for ( ; it2.idx() < end; it2.top().forwardIdx())
3335                 buffer().updateLabels(it2);
3336
3337         //reset afterwards
3338         if (tabular.is_long_tabular)
3339                 cnts.current_float(saveflt);
3340 }
3341
3342
3343 void InsetTabular::doDispatch(Cursor & cur, FuncRequest & cmd)
3344 {
3345         LYXERR(Debug::DEBUG, "# InsetTabular::doDispatch: cmd: " << cmd
3346                              << "\n  cur:" << cur);
3347         CursorSlice sl = cur.top();
3348         Cursor & bvcur = cur.bv().cursor();
3349
3350         switch (cmd.action) {
3351
3352         case LFUN_MOUSE_PRESS: {
3353                 //lyxerr << "# InsetTabular::MousePress\n" << cur.bv().cursor() << endl;
3354                 // select row
3355                 if (cmd.x < xo(cur.bv()) + ADD_TO_TABULAR_WIDTH
3356                         || cmd.x > xo(cur.bv()) + tabular.width()) {
3357                         row_type r = rowFromY(cur, cmd.y);
3358                         cur.idx() = tabular.getFirstCellInRow(r);
3359                         cur.pos() = 0;
3360                         cur.resetAnchor();
3361                         cur.idx() = tabular.getLastCellInRow(r);
3362                         cur.pos() = cur.lastpos();
3363                         cur.setSelection(true);
3364                         bvcur = cur; 
3365                         rowselect_ = true;
3366                         break;
3367                 }
3368                 // select column
3369                 int const y0 = yo(cur.bv()) - tabular.rowAscent(0);
3370                 if (cmd.y < y0 + ADD_TO_TABULAR_WIDTH 
3371                         || cmd.y > y0 + tabular.height()) {
3372                         col_type c = columnFromX(cur, cmd.x);
3373                         cur.idx() = tabular.cellIndex(0, c);
3374                         cur.pos() = 0;
3375                         cur.resetAnchor();
3376                         cur.idx() = tabular.cellIndex(tabular.row_info.size() - 1, c);
3377                         cur.pos() = cur.lastpos();
3378                         cur.setSelection(true);
3379                         bvcur = cur; 
3380                         colselect_ = true;
3381                         break;
3382                 }
3383                 // do not reset cursor/selection if we have selected
3384                 // some cells (bug 2715).
3385                 if (cmd.button() == mouse_button::button3
3386                     && &bvcur.selBegin().inset() == this 
3387                     && bvcur.selIsMultiCell()) 
3388                         ;
3389                 else
3390                         // Let InsetTableCell do it
3391                         cell(cur.idx())->dispatch(cur, cmd);
3392                 break;
3393         }
3394         case LFUN_MOUSE_MOTION:
3395                 //lyxerr << "# InsetTabular::MouseMotion\n" << bvcur << endl;
3396                 if (cmd.button() == mouse_button::button1) {
3397                         // only accept motions to places not deeper nested than the real anchor
3398                         if (!bvcur.anchor_.hasPart(cur)) {
3399                                 cur.undispatched();
3400                                 break;
3401                         }
3402                         // select (additional) row
3403                         if (rowselect_) {
3404                                 row_type r = rowFromY(cur, cmd.y);
3405                                 cur.idx() = tabular.getLastCellInRow(r);
3406                                 // we need to reset the cursor's pit and pos now, as the old ones
3407                                 // may no longer be valid.
3408                                 cur.pit() = 0;
3409                                 cur.pos() = 0;
3410                                 bvcur.setCursor(cur);
3411                                 bvcur.setSelection(true);
3412                                 break;
3413                         }
3414                         // select (additional) column
3415                         if (colselect_) {
3416                                 col_type c = columnFromX(cur, cmd.x);
3417                                 cur.idx() = tabular.cellIndex(tabular.row_info.size() - 1, c);
3418                                 // we need to reset the cursor's pit and pos now, as the old ones
3419                                 // may no longer be valid.
3420                                 cur.pit() = 0;
3421                                 cur.pos() = 0;
3422                                 bvcur.setCursor(cur);
3423                                 bvcur.setSelection(true);
3424                                 break;
3425                         }
3426                         // only update if selection changes
3427                         if (bvcur.idx() == cur.idx() &&
3428                                 !(bvcur.anchor_.idx() == cur.idx() && bvcur.pos() != cur.pos()))
3429                                 cur.noUpdate();
3430                         setCursorFromCoordinates(cur, cmd.x, cmd.y);
3431                         bvcur.setCursor(cur);
3432                         bvcur.setSelection(true);
3433                         // if this is a multicell selection, we just set the cursor to
3434                         // the beginning of the cell's text.
3435                         if (bvcur.selIsMultiCell()) {
3436                                 bvcur.pit() = bvcur.lastpit();
3437                                 bvcur.pos() = bvcur.lastpos();
3438                         }
3439                 }
3440                 break;
3441
3442         case LFUN_MOUSE_RELEASE:
3443                 rowselect_ = false;
3444                 colselect_ = false;
3445                 break;
3446
3447         case LFUN_CELL_BACKWARD:
3448                 movePrevCell(cur);
3449                 cur.setSelection(false);
3450                 break;
3451
3452         case LFUN_CELL_FORWARD:
3453                 moveNextCell(cur);
3454                 cur.setSelection(false);
3455                 break;
3456
3457         case LFUN_CHAR_FORWARD_SELECT:
3458         case LFUN_CHAR_FORWARD:
3459         case LFUN_CHAR_BACKWARD_SELECT:
3460         case LFUN_CHAR_BACKWARD:
3461         case LFUN_CHAR_RIGHT_SELECT:
3462         case LFUN_CHAR_RIGHT:
3463         case LFUN_CHAR_LEFT_SELECT:
3464         case LFUN_CHAR_LEFT: {
3465                 // determine whether we move to next or previous cell, where to enter 
3466                 // the new cell from, and which command to "finish" (i.e., exit the
3467                 // inset) with:
3468                 bool next_cell;
3469                 EntryDirection entry_from = ENTRY_DIRECTION_IGNORE;
3470                 FuncCode finish_lfun;
3471
3472                 if (cmd.action == LFUN_CHAR_FORWARD 
3473                                 || cmd.action == LFUN_CHAR_FORWARD_SELECT) {
3474                         next_cell = true;
3475                         finish_lfun = LFUN_FINISHED_FORWARD;
3476                 }
3477                 else if (cmd.action == LFUN_CHAR_BACKWARD
3478                                 || cmd.action == LFUN_CHAR_BACKWARD_SELECT) {
3479                         next_cell = false;
3480                         finish_lfun = LFUN_FINISHED_BACKWARD;
3481                 }
3482                 // LEFT or RIGHT commands --- the interpretation will depend on the 
3483                 // table's direction.
3484                 else {
3485                         bool const right = cmd.action == LFUN_CHAR_RIGHT
3486                                 || cmd.action == LFUN_CHAR_RIGHT_SELECT;
3487                         next_cell = isRightToLeft(cur) != right;
3488                         
3489                         if (lyxrc.visual_cursor)
3490                                 entry_from = right ? ENTRY_DIRECTION_LEFT:ENTRY_DIRECTION_RIGHT;
3491
3492                         finish_lfun = right ? LFUN_FINISHED_RIGHT : LFUN_FINISHED_LEFT;
3493                 }
3494
3495                 bool const select = cmd.action == LFUN_CHAR_FORWARD_SELECT ||
3496                     cmd.action == LFUN_CHAR_BACKWARD_SELECT ||
3497                     cmd.action == LFUN_CHAR_RIGHT_SELECT ||
3498                     cmd.action == LFUN_CHAR_LEFT_SELECT;
3499
3500                 // If we have a multicell selection or we're 
3501                 // not doing some LFUN_*_SELECT thing anyway...
3502                 if (!cur.selIsMultiCell() || !select) {
3503                         col_type const c = tabular.cellColumn(cur.idx());
3504                         row_type const r = tabular.cellRow(cur.idx());
3505                         // Are we trying to select the whole cell and is the whole cell 
3506                         // not yet selected?
3507                         bool const select_whole = select && !isCellSelected(cur, r, c) &&
3508                                 ((next_cell && cur.pit() == cur.lastpit() 
3509                                 && cur.pos() == cur.lastpos())
3510                                 || (!next_cell && cur.pit() == 0 && cur.pos() == 0));
3511
3512                         bool const empty_cell = cur.lastpos() == 0 && cur.lastpit() == 0;
3513
3514                         // ...try to dispatch to the cell's inset.
3515                         cell(cur.idx())->dispatch(cur, cmd);
3516
3517                         // When we already have a selection we want to select the whole cell
3518                         // before going to the next cell.
3519                         if (select_whole && !empty_cell){
3520                                 getText(cur.idx())->selectAll(cur);
3521                                 cur.dispatched();
3522                                 break;
3523                         }
3524
3525                         // FIXME: When we support the selection of an empty cell, remove 
3526                         // the !empty_cell from this condition. For now we jump to the next
3527                         // cell if the current cell is empty.
3528                         if (cur.result().dispatched() && !empty_cell)
3529                                 break;
3530                 }
3531
3532                 // move to next/prev cell, as appropriate
3533                 // note that we will always do this if we're selecting and we have
3534                 // a multicell selection
3535                 LYXERR(Debug::RTL, "entering " << (next_cell ? "next" : "previous")
3536                         << " cell from: " << int(entry_from));
3537                 if (next_cell)
3538                         moveNextCell(cur, entry_from);
3539                 else
3540                         movePrevCell(cur, entry_from);
3541                 // if we're exiting the table, call the appropriate FINISHED lfun
3542                 if (sl == cur.top())
3543                         cmd = FuncRequest(finish_lfun);
3544                 else
3545                         cur.dispatched();
3546                 break;
3547
3548         }
3549
3550         case LFUN_DOWN_SELECT:
3551         case LFUN_DOWN:
3552                 if (!(cur.selection() && cur.selIsMultiCell()))
3553                         cell(cur.idx())->dispatch(cur, cmd);
3554                 
3555                 cur.dispatched(); // override the cell's decision
3556                 if (sl == cur.top()) {
3557                         // if our Text didn't do anything to the cursor
3558                         // then we try to put the cursor into the cell below
3559                         // setting also the right targetX.
3560                         cur.selHandle(cmd.action == LFUN_DOWN_SELECT);
3561                         if (tabular.cellRow(cur.idx()) != tabular.row_info.size() - 1) {
3562                                 cur.idx() = tabular.cellBelow(cur.idx());
3563                                 cur.pit() = 0;
3564                                 TextMetrics const & tm =
3565                                         cur.bv().textMetrics(cell(cur.idx())->getText(0));
3566                                 cur.pos() = tm.x2pos(cur.pit(), 0, cur.targetX());
3567                         }
3568                 }
3569                 if (sl == cur.top()) {
3570                         // we trick it to go to forward after leaving the
3571                         // tabular.
3572                         cmd = FuncRequest(LFUN_FINISHED_FORWARD);
3573                         cur.undispatched();
3574                 }
3575                 if (cur.selIsMultiCell()) {
3576                         cur.pit() = cur.lastpit();
3577                         cur.pos() = cur.lastpos();
3578                         return;
3579                 }
3580                 break;
3581
3582         case LFUN_UP_SELECT:
3583         case LFUN_UP:
3584                 if (!(cur.selection() && cur.selIsMultiCell()))
3585                         cell(cur.idx())->dispatch(cur, cmd);
3586                 cur.dispatched(); // override the cell's decision
3587                 if (sl == cur.top()) {
3588                         // if our Text didn't do anything to the cursor
3589                         // then we try to put the cursor into the cell above
3590                         // setting also the right targetX.
3591                         cur.selHandle(cmd.action == LFUN_UP_SELECT);
3592                         if (tabular.cellRow(cur.idx()) != 0) {
3593                                 cur.idx() = tabular.cellAbove(cur.idx());
3594                                 cur.pit() = cur.lastpit();
3595                                 Text const * text = cell(cur.idx())->getText(0);
3596                                 TextMetrics const & tm = cur.bv().textMetrics(text);
3597                                 ParagraphMetrics const & pm =
3598                                         tm.parMetrics(cur.lastpit());
3599                                 cur.pos() = tm.x2pos(cur.pit(), pm.rows().size()-1, cur.targetX());
3600                         }
3601                 }
3602                 if (sl == cur.top()) {
3603                         cmd = FuncRequest(LFUN_UP);
3604                         cur.undispatched();
3605                 }
3606                 if (cur.selIsMultiCell()) {
3607                         cur.pit() = 0;
3608                         cur.pos() = cur.lastpos();
3609                         return;
3610                 }
3611                 break;
3612
3613 //      case LFUN_SCREEN_DOWN: {
3614 //              //if (hasSelection())
3615 //              //      cur.selection() = false;
3616 //              col_type const col = tabular.cellColumn(cur.idx());
3617 //              int const t =   cur.bv().top_y() + cur.bv().height();
3618 //              if (t < yo() + tabular.getHeightOfTabular()) {
3619 //                      cur.bv().scrollDocView(t);
3620 //                      cur.idx() = tabular.cellBelow(first_visible_cell) + col;
3621 //              } else {
3622 //                      cur.idx() = tabular.getFirstCellInRow(tabular.rows() - 1) + col;
3623 //              }
3624 //              cur.par() = 0;
3625 //              cur.pos() = 0;
3626 //              break;
3627 //      }
3628 //
3629 //      case LFUN_SCREEN_UP: {
3630 //              //if (hasSelection())
3631 //              //      cur.selection() = false;
3632 //              col_type const col = tabular.cellColumn(cur.idx());
3633 //              int const t =   cur.bv().top_y() + cur.bv().height();
3634 //              if (yo() < 0) {
3635 //                      cur.bv().scrollDocView(t);
3636 //                      if (yo() > 0)
3637 //                              cur.idx() = col;
3638 //                      else
3639 //                              cur.idx() = tabular.cellBelow(first_visible_cell) + col;
3640 //              } else {
3641 //                      cur.idx() = col;
3642 //              }
3643 //              cur.par() = cur.lastpar();
3644 //              cur.pos() = cur.lastpos();
3645 //              break;
3646 //      }
3647
3648         case LFUN_LAYOUT_TABULAR:
3649                 cur.bv().showDialog("tabular", params2string(*this), this);
3650                 break;
3651
3652         case LFUN_INSET_DIALOG_UPDATE:
3653                 cur.bv().updateDialog("tabular", params2string(*this));
3654                 break;
3655
3656         case LFUN_TABULAR_FEATURE:
3657                 if (!tabularFeatures(cur, to_utf8(cmd.argument())))
3658                         cur.undispatched();
3659                 break;
3660
3661         // insert file functions
3662         case LFUN_FILE_INSERT_PLAINTEXT_PARA:
3663         case LFUN_FILE_INSERT_PLAINTEXT:
3664                 // FIXME UNICODE
3665                 if (FileName::isAbsolute(to_utf8(cmd.argument()))) {
3666                         docstring const tmpstr = cur.bv().contentsOfPlaintextFile(
3667                                 FileName(to_utf8(cmd.argument())));
3668                         if (tmpstr.empty())
3669                                 break;
3670                         cur.recordUndoInset(INSERT_UNDO);
3671                         if (insertPlaintextString(cur.bv(), tmpstr, false)) {
3672                                 // content has been replaced,
3673                                 // so cursor might be invalid
3674                                 cur.pos() = cur.lastpos();
3675                                 cur.pit() = cur.lastpit();
3676                                 bvcur.setCursor(cur);
3677                         } else
3678                                 cur.undispatched();
3679                 }
3680                 break;
3681
3682         case LFUN_CUT:
3683                 if (cur.selIsMultiCell()) {
3684                         if (copySelection(cur)) {
3685                                 cur.recordUndoInset(DELETE_UNDO);
3686                                 cutSelection(cur);
3687                         }
3688                 } else
3689                         cell(cur.idx())->dispatch(cur, cmd);
3690                 break;
3691
3692         case LFUN_SELF_INSERT:
3693                 if (cur.selIsMultiCell()) {
3694                         cur.recordUndoInset(DELETE_UNDO);
3695                         cutSelection(cur);
3696                 }
3697                 cell(cur.idx())->dispatch(cur, cmd);
3698                 break;
3699
3700         case LFUN_CHAR_DELETE_BACKWARD:
3701         case LFUN_CHAR_DELETE_FORWARD:
3702                 if (cur.selIsMultiCell()) {
3703                         cur.recordUndoInset(DELETE_UNDO);
3704                         cutSelection(cur);
3705                 } else
3706                         cell(cur.idx())->dispatch(cur, cmd);
3707                 break;
3708
3709         case LFUN_COPY:
3710                 if (!cur.selection())
3711                         break;
3712                 if (cur.selIsMultiCell()) {
3713                         cur.finishUndo();
3714                         copySelection(cur);
3715                 } else
3716                         cell(cur.idx())->dispatch(cur, cmd);
3717                 break;
3718
3719         case LFUN_CLIPBOARD_PASTE:
3720         case LFUN_PRIMARY_SELECTION_PASTE: {
3721                 docstring const clip = (cmd.action == LFUN_CLIPBOARD_PASTE) ?
3722                         theClipboard().getAsText() :
3723                         theSelection().get();
3724                 if (clip.empty())
3725                         break;
3726                 // pass to InsertPlaintextString, but
3727                 // only if we have multi-cell content
3728                 if (clip.find_first_of(from_ascii("\t\n")) != docstring::npos) {
3729                         cur.recordUndoInset(INSERT_UNDO);
3730                         if (insertPlaintextString(cur.bv(), clip, false)) {
3731                                 // content has been replaced,
3732                                 // so cursor might be invalid
3733                                 cur.pos() = cur.lastpos();
3734                                 cur.pit() = cur.lastpit();
3735                                 bvcur.setCursor(cur);
3736                                 break;
3737                         }
3738                 }
3739                 // Let the cell handle normal text
3740                 cell(cur.idx())->dispatch(cur, cmd);
3741                 break;
3742         }
3743
3744         case LFUN_PASTE:
3745                 if (!tabularStackDirty()) {
3746                         if (!cur.selIsMultiCell())
3747                                 cell(cur.idx())->dispatch(cur, cmd);
3748                         break;
3749                 }
3750                 if (theClipboard().isInternal() ||
3751                     (!theClipboard().hasInternal() && theClipboard().hasLyXContents())) {
3752                         cur.recordUndoInset(INSERT_UNDO);
3753                         pasteClipboard(cur);
3754                 }
3755                 break;
3756
3757         case LFUN_FONT_EMPH:
3758         case LFUN_FONT_BOLD:
3759         case LFUN_FONT_BOLDSYMBOL:
3760         case LFUN_FONT_ROMAN:
3761         case LFUN_FONT_NOUN:
3762         case LFUN_FONT_ITAL:
3763         case LFUN_FONT_FRAK:
3764         case LFUN_FONT_TYPEWRITER:
3765         case LFUN_FONT_SANS:
3766         case LFUN_TEXTSTYLE_APPLY:
3767         case LFUN_TEXTSTYLE_UPDATE:
3768         case LFUN_FONT_SIZE:
3769         case LFUN_FONT_UNDERLINE:
3770         case LFUN_FONT_STRIKEOUT:
3771         case LFUN_FONT_UULINE:
3772         case LFUN_FONT_UWAVE:
3773         case LFUN_LANGUAGE:
3774         case LFUN_WORD_CAPITALIZE:
3775         case LFUN_WORD_UPCASE:
3776         case LFUN_WORD_LOWCASE:
3777         case LFUN_CHARS_TRANSPOSE:
3778                 if (cur.selIsMultiCell()) {
3779                         row_type rs, re;
3780                         col_type cs, ce;
3781                         getSelection(cur, rs, re, cs, ce);
3782                         Cursor tmpcur = cur;
3783                         for (row_type i = rs; i <= re; ++i) {
3784                                 for (col_type j = cs; j <= ce; ++j) {
3785                                         // cursor follows cell:
3786                                         tmpcur.idx() = tabular.cellIndex(i, j);
3787                                         // select this cell only:
3788                                         tmpcur.pit() = 0;
3789                                         tmpcur.pos() = 0;
3790                                         tmpcur.resetAnchor();
3791                                         tmpcur.pit() = tmpcur.lastpit();
3792                                         tmpcur.pos() = tmpcur.top().lastpos();
3793                                         tmpcur.setCursor(tmpcur);
3794                                         tmpcur.setSelection();
3795                                         cell(tmpcur.idx())->dispatch(tmpcur, cmd);
3796                                 }
3797                         }
3798                         break;
3799                 } else {
3800                         cell(cur.idx())->dispatch(cur, cmd);
3801                         break;
3802                 }
3803
3804         case LFUN_INSET_SETTINGS:
3805                 // relay this lfun to Inset, not to the cell.
3806                 Inset::doDispatch(cur, cmd);
3807                 break;
3808
3809         default:
3810                 // we try to handle this event in the insets dispatch function.
3811                 cell(cur.idx())->dispatch(cur, cmd);
3812                 break;
3813         }
3814 }
3815
3816
3817 // function sets an object as defined in func_status.h:
3818 // states OK, Unknown, Disabled, On, Off.
3819 bool InsetTabular::getStatus(Cursor & cur, FuncRequest const & cmd,
3820         FuncStatus & status) const
3821 {
3822         switch (cmd.action) {
3823         case LFUN_TABULAR_FEATURE: {
3824                 int action = Tabular::LAST_ACTION;
3825                 int i = 0;
3826                 for (; tabularFeature[i].action != Tabular::LAST_ACTION; ++i) {
3827                         string const tmp = tabularFeature[i].feature;
3828                         if (tmp == to_utf8(cmd.argument()).substr(0, tmp.length())) {
3829                                 action = tabularFeature[i].action;
3830                                 break;
3831                         }
3832                 }
3833                 if (action == Tabular::LAST_ACTION) {
3834                         status.clear();
3835                         status.unknown(true);
3836                         return true;
3837                 }
3838
3839                 string const argument
3840                         = ltrim(to_utf8(cmd.argument()).substr(tabularFeature[i].feature.length()));
3841
3842                 row_type sel_row_start = 0;
3843                 row_type sel_row_end = 0;
3844                 col_type sel_col_start = 0;
3845                 col_type sel_col_end = 0;
3846                 Tabular::ltType dummyltt;
3847                 bool flag = true;
3848
3849                 getSelection(cur, sel_row_start, sel_row_end, sel_col_start, sel_col_end);
3850
3851                 switch (action) {
3852                 case Tabular::SET_PWIDTH:
3853                 case Tabular::SET_MPWIDTH:
3854                 case Tabular::SET_SPECIAL_COLUMN:
3855                 case Tabular::SET_SPECIAL_MULTI:
3856                 case Tabular::APPEND_ROW:
3857                 case Tabular::APPEND_COLUMN:
3858                 case Tabular::DELETE_ROW:
3859                 case Tabular::DELETE_COLUMN:
3860                 case Tabular::COPY_ROW:
3861                 case Tabular::COPY_COLUMN:
3862                 case Tabular::SET_TOP_SPACE:
3863                 case Tabular::SET_BOTTOM_SPACE:
3864                 case Tabular::SET_INTERLINE_SPACE:
3865                         status.clear();
3866                         return true;
3867
3868                 case Tabular::MULTICOLUMN:
3869                         // If a row is set as longtable caption, it must not be allowed
3870                         // to unset that this row is a multicolumn.
3871                         status.setEnabled(sel_row_start == sel_row_end
3872                                 && !tabular.ltCaption(tabular.cellRow(cur.idx())));
3873                         status.setOnOff(tabular.isMultiColumn(cur.idx()));
3874                         break;
3875
3876                 case Tabular::SET_ALL_LINES:
3877                 case Tabular::UNSET_ALL_LINES:
3878                 case Tabular::SET_BORDER_LINES:
3879                         status.setEnabled(!tabular.ltCaption(tabular.cellRow(cur.idx())));
3880                         break;
3881
3882                 case Tabular::TOGGLE_LINE_TOP:
3883                         status.setEnabled(!tabular.ltCaption(tabular.cellRow(cur.idx())));
3884                         status.setOnOff(tabular.topLine(cur.idx()));
3885                         break;
3886
3887                 case Tabular::TOGGLE_LINE_BOTTOM:
3888                         status.setEnabled(!tabular.ltCaption(tabular.cellRow(cur.idx())));
3889                         status.setOnOff(tabular.bottomLine(cur.idx()));
3890                         break;
3891
3892                 case Tabular::TOGGLE_LINE_LEFT:
3893                         status.setEnabled(!tabular.ltCaption(tabular.cellRow(cur.idx())));
3894                         status.setOnOff(tabular.leftLine(cur.idx()));
3895                         break;
3896
3897                 case Tabular::TOGGLE_LINE_RIGHT:
3898                         status.setEnabled(!tabular.ltCaption(tabular.cellRow(cur.idx())));
3899                         status.setOnOff(tabular.rightLine(cur.idx()));
3900                         break;
3901
3902                 case Tabular::M_ALIGN_LEFT:
3903                         flag = false;
3904                 case Tabular::ALIGN_LEFT:
3905                         status.setOnOff(tabular.getAlignment(cur.idx(), flag) == LYX_ALIGN_LEFT);
3906                         break;
3907
3908                 case Tabular::M_ALIGN_RIGHT:
3909                         flag = false;
3910                 case Tabular::ALIGN_RIGHT:
3911                         status.setOnOff(tabular.getAlignment(cur.idx(), flag) == LYX_ALIGN_RIGHT);
3912                         break;
3913
3914                 case Tabular::M_ALIGN_CENTER:
3915                         flag = false;
3916                 case Tabular::ALIGN_CENTER:
3917                         status.setOnOff(tabular.getAlignment(cur.idx(), flag) == LYX_ALIGN_CENTER);
3918                         break;
3919
3920                 case Tabular::ALIGN_BLOCK:
3921                         status.setEnabled(!tabular.getPWidth(cur.idx()).zero());
3922                         status.setOnOff(tabular.getAlignment(cur.idx(), flag) == LYX_ALIGN_BLOCK);
3923                         break;
3924
3925                 case Tabular::M_VALIGN_TOP:
3926                         flag = false;
3927                 case Tabular::VALIGN_TOP:
3928                         status.setOnOff(
3929                                 tabular.getVAlignment(cur.idx(), flag) == Tabular::LYX_VALIGN_TOP);
3930                         break;
3931
3932                 case Tabular::M_VALIGN_BOTTOM:
3933                         flag = false;
3934                 case Tabular::VALIGN_BOTTOM:
3935                         status.setOnOff(
3936                                 tabular.getVAlignment(cur.idx(), flag) == Tabular::LYX_VALIGN_BOTTOM);
3937                         break;
3938
3939                 case Tabular::M_VALIGN_MIDDLE:
3940                         flag = false;
3941                 case Tabular::VALIGN_MIDDLE:
3942                         status.setOnOff(
3943                                 tabular.getVAlignment(cur.idx(), flag) == Tabular::LYX_VALIGN_MIDDLE);
3944                         break;
3945
3946                 case Tabular::SET_LONGTABULAR:
3947                         status.setOnOff(tabular.is_long_tabular);
3948                         break;
3949
3950                 case Tabular::UNSET_LONGTABULAR:
3951                         status.setOnOff(!tabular.is_long_tabular);
3952                         break;
3953
3954                 case Tabular::TOGGLE_ROTATE_TABULAR:
3955                 case Tabular::SET_ROTATE_TABULAR:
3956                         status.setOnOff(tabular.rotate);
3957                         break;
3958
3959                 case Tabular::TABULAR_VALIGN_TOP:
3960                         status.setOnOff(tabular.tabular_valignment 
3961                                 == Tabular::LYX_VALIGN_TOP);
3962                         break;
3963                 case Tabular::TABULAR_VALIGN_MIDDLE:
3964                         status.setOnOff(tabular.tabular_valignment 
3965                                 == Tabular::LYX_VALIGN_MIDDLE);
3966                         break;
3967                 case Tabular::TABULAR_VALIGN_BOTTOM:
3968                         status.setOnOff(tabular.tabular_valignment 
3969                                 == Tabular::LYX_VALIGN_BOTTOM);
3970                         break;
3971
3972                 case Tabular::LONGTABULAR_ALIGN_LEFT:
3973                         status.setOnOff(tabular.longtabular_alignment 
3974                                 == Tabular::LYX_LONGTABULAR_ALIGN_LEFT);
3975                         break;
3976                 case Tabular::LONGTABULAR_ALIGN_CENTER:
3977                         status.setOnOff(tabular.longtabular_alignment 
3978                                 == Tabular::LYX_LONGTABULAR_ALIGN_CENTER);
3979                         break;
3980                 case Tabular::LONGTABULAR_ALIGN_RIGHT:
3981                         status.setOnOff(tabular.longtabular_alignment 
3982                                 == Tabular::LYX_LONGTABULAR_ALIGN_RIGHT);
3983                         break;
3984
3985                 case Tabular::UNSET_ROTATE_TABULAR:
3986                         status.setOnOff(!tabular.rotate);
3987                         break;
3988
3989                 case Tabular::TOGGLE_ROTATE_CELL:
3990                 case Tabular::SET_ROTATE_CELL:
3991                         status.setOnOff(!oneCellHasRotationState(false,
3992                                 sel_row_start, sel_row_end, sel_col_start, sel_col_end));
3993                         break;
3994
3995                 case Tabular::UNSET_ROTATE_CELL:
3996                         status.setOnOff(!oneCellHasRotationState(true,
3997                                 sel_row_start, sel_row_end, sel_col_start, sel_col_end));
3998                         break;
3999
4000                 case Tabular::SET_USEBOX:
4001                         status.setOnOff(convert<int>(argument) == tabular.getUsebox(cur.idx()));
4002                         break;
4003
4004                 // every row can only be one thing:
4005                 // either a footer or header or caption
4006                 case Tabular::SET_LTFIRSTHEAD:
4007                         status.setEnabled(sel_row_start == sel_row_end
4008                                 && !tabular.ltCaption(sel_row_start));
4009                         status.setOnOff(tabular.getRowOfLTFirstHead(sel_row_start, dummyltt));
4010                         break;
4011
4012                 case Tabular::UNSET_LTFIRSTHEAD:
4013                         status.setOnOff(!tabular.getRowOfLTFirstHead(sel_row_start, dummyltt));
4014                         break;
4015
4016                 case Tabular::SET_LTHEAD:
4017                         status.setEnabled(sel_row_start == sel_row_end
4018                                 && !tabular.ltCaption(sel_row_start));
4019                         status.setOnOff(tabular.getRowOfLTHead(sel_row_start, dummyltt));
4020                         break;
4021
4022                 case Tabular::UNSET_LTHEAD:
4023                         status.setOnOff(!tabular.getRowOfLTHead(sel_row_start, dummyltt));
4024                         break;
4025
4026                 case Tabular::SET_LTFOOT:
4027                         status.setEnabled(sel_row_start == sel_row_end
4028                                 && !tabular.ltCaption(sel_row_start));
4029                         status.setOnOff(tabular.getRowOfLTFoot(sel_row_start, dummyltt));
4030                         break;
4031
4032                 case Tabular::UNSET_LTFOOT:
4033                         status.setOnOff(!tabular.getRowOfLTFoot(sel_row_start, dummyltt));
4034                         break;
4035
4036                 case Tabular::SET_LTLASTFOOT:
4037                         status.setEnabled(sel_row_start == sel_row_end
4038                                 && !tabular.ltCaption(sel_row_start));
4039                         status.setOnOff(tabular.getRowOfLTLastFoot(sel_row_start, dummyltt));
4040                         break;
4041
4042                 case Tabular::UNSET_LTLASTFOOT:
4043                         status.setOnOff(!tabular.getRowOfLTLastFoot(sel_row_start, dummyltt));
4044                         break;
4045
4046                 case Tabular::SET_LTNEWPAGE:
4047                         status.setOnOff(tabular.getLTNewPage(sel_row_start));
4048                         break;
4049
4050                 // only one row can be the caption
4051                 case Tabular::TOGGLE_LTCAPTION:
4052                         status.setEnabled(sel_row_start == sel_row_end
4053                                 && !tabular.getRowOfLTFirstHead(sel_row_start, dummyltt)
4054                                 && !tabular.getRowOfLTHead(sel_row_start, dummyltt)
4055                                 && !tabular.getRowOfLTFoot(sel_row_start, dummyltt)
4056                                 && !tabular.getRowOfLTLastFoot(sel_row_start, dummyltt)
4057                                 && (!tabular.haveLTCaption()
4058                                         || tabular.ltCaption(sel_row_start)));
4059                         status.setOnOff(tabular.ltCaption(sel_row_start));
4060                         break;
4061
4062                 case Tabular::SET_BOOKTABS:
4063                         status.setOnOff(tabular.use_booktabs);
4064                         break;
4065
4066                 case Tabular::UNSET_BOOKTABS:
4067                         status.setOnOff(!tabular.use_booktabs);
4068                         break;
4069
4070                 default:
4071                         status.clear();
4072                         status.setEnabled(false);
4073                         break;
4074                 }
4075                 return true;
4076         }
4077
4078         // These are only enabled inside tabular
4079         case LFUN_CELL_BACKWARD:
4080         case LFUN_CELL_FORWARD:
4081                 status.setEnabled(true);
4082                 return true;
4083
4084         // disable these with multiple cells selected
4085         case LFUN_INSET_INSERT:
4086         case LFUN_TABULAR_INSERT:
4087         case LFUN_FLEX_INSERT:
4088         case LFUN_FLOAT_INSERT:
4089         case LFUN_FLOAT_WIDE_INSERT:
4090         case LFUN_FOOTNOTE_INSERT:
4091         case LFUN_MARGINALNOTE_INSERT:
4092         case LFUN_MATH_INSERT:
4093         case LFUN_MATH_MODE:
4094         case LFUN_MATH_MUTATE:
4095         case LFUN_MATH_DISPLAY:
4096         case LFUN_NOTE_INSERT:
4097         case LFUN_OPTIONAL_INSERT:
4098         case LFUN_BOX_INSERT:
4099         case LFUN_BRANCH_INSERT:
4100         case LFUN_PHANTOM_INSERT:
4101         case LFUN_WRAP_INSERT:
4102         case LFUN_ERT_INSERT: {
4103                 if (cur.selIsMultiCell()) {
4104                         status.setEnabled(false);
4105                         return true;
4106                 } else
4107                         return cell(cur.idx())->getStatus(cur, cmd, status);
4108         }
4109
4110         // disable in non-fixed-width cells
4111         case LFUN_NEWLINE_INSERT:
4112         case LFUN_BREAK_PARAGRAPH: {
4113                 if (tabular.getPWidth(cur.idx()).zero()) {
4114                         status.setEnabled(false);
4115                         return true;
4116                 } else
4117                         return cell(cur.idx())->getStatus(cur, cmd, status);
4118         }
4119
4120         case LFUN_NEWPAGE_INSERT:
4121                 status.setEnabled(false);
4122                 return true;
4123
4124         case LFUN_PASTE:
4125                 if (tabularStackDirty() && theClipboard().isInternal()) {
4126                         if (cur.selIsMultiCell()) {
4127                                 row_type rs, re;
4128                                 col_type cs, ce;
4129                                 getSelection(cur, rs, re, cs, ce);
4130                                 if (paste_tabular && paste_tabular->column_info.size() == ce - cs + 1
4131                                           && paste_tabular->row_info.size() == re - rs + 1)
4132                                         status.setEnabled(true);        
4133                                 else {
4134                                         status.setEnabled(false);
4135                                         status.message(_("Selection size should match clipboard content."));
4136                                 }
4137                         } else
4138                                 status.setEnabled(true);
4139                         return true;
4140                 }
4141                 return cell(cur.idx())->getStatus(cur, cmd, status);
4142
4143         case LFUN_INSET_SETTINGS:
4144                 // relay this lfun to Inset, not to the cell.
4145                 return Inset::getStatus(cur, cmd, status);
4146
4147         case LFUN_INSET_MODIFY:
4148                 if (insetCode(cmd.getArg(0)) == TABULAR_CODE) {
4149                         status.setEnabled(true);
4150                         return true;
4151                 }
4152                 // Fall through
4153
4154         default:
4155                 // we try to handle this event in the insets dispatch function.
4156                 return cell(cur.idx())->getStatus(cur, cmd, status);
4157         }
4158 }
4159
4160
4161 Inset::DisplayType InsetTabular::display() const
4162 {
4163                 if (tabular.is_long_tabular) {
4164                         switch (tabular.longtabular_alignment) {
4165                         case Tabular::LYX_LONGTABULAR_ALIGN_LEFT:
4166                                 return AlignLeft;
4167                         case Tabular::LYX_LONGTABULAR_ALIGN_CENTER:
4168                                 return AlignCenter;
4169                         case Tabular::LYX_LONGTABULAR_ALIGN_RIGHT:
4170                                 return AlignRight;
4171                         default:
4172                                 return AlignCenter;
4173                         }
4174                 } else
4175                         return Inline;
4176 }
4177
4178
4179 int InsetTabular::latex(odocstream & os, OutputParams const & runparams) const
4180 {
4181         return tabular.latex(os, runparams);
4182 }
4183
4184
4185 int InsetTabular::plaintext(odocstream & os, OutputParams const & runparams) const
4186 {
4187         os << '\n'; // output table on a new line
4188         int const dp = runparams.linelen > 0 ? runparams.depth : 0;
4189         tabular.plaintext(os, runparams, dp, false, 0);
4190         return PLAINTEXT_NEWLINE;
4191 }
4192
4193
4194 int InsetTabular::docbook(odocstream & os, OutputParams const & runparams) const
4195 {
4196         int ret = 0;
4197         Inset * master = 0;
4198
4199         // FIXME: Why not pass a proper DocIterator here?
4200 #if 0
4201         // if the table is inside a float it doesn't need the informaltable
4202         // wrapper. Search for it.
4203         for (master = owner(); master; master = master->owner())
4204                 if (master->lyxCode() == FLOAT_CODE)
4205                         break;
4206 #endif
4207
4208         if (!master) {
4209                 os << "<informaltable>";
4210                 ++ret;
4211         }
4212         ret += tabular.docbook(os, runparams);
4213         if (!master) {
4214                 os << "</informaltable>";
4215                 ++ret;
4216         }
4217         return ret;
4218 }
4219
4220
4221 void InsetTabular::validate(LaTeXFeatures & features) const
4222 {
4223         tabular.validate(features);
4224 }
4225
4226
4227 shared_ptr<InsetTableCell const> InsetTabular::cell(idx_type idx) const
4228 {
4229         return tabular.cellInset(idx);
4230 }
4231
4232
4233 shared_ptr<InsetTableCell> InsetTabular::cell(idx_type idx)
4234 {
4235         return tabular.cellInset(idx);
4236 }
4237
4238
4239 void InsetTabular::cursorPos(BufferView const & bv,
4240                 CursorSlice const & sl, bool boundary, int & x, int & y) const
4241 {
4242         cell(sl.idx())->cursorPos(bv, sl, boundary, x, y);
4243
4244         // y offset     correction
4245         int const row = tabular.cellRow(sl.idx());
4246         for (int i = 0; i <= row; ++i) {
4247                 if (i != 0) {
4248                         y += tabular.rowAscent(i);
4249                         y += tabular.getAdditionalHeight(i);
4250                 }
4251                 if (i != row)
4252                         y += tabular.rowDescent(i);
4253         }
4254
4255         // x offset correction
4256         int const col = tabular.cellColumn(sl.idx());
4257         int idx = tabular.cellIndex(row, 0);
4258         for (int j = 0; j < col; ++j) {
4259                 if (tabular.isPartOfMultiColumn(row, j))
4260                         continue;
4261                 x += tabular.columnWidth(idx);
4262                 ++idx;
4263         }
4264         x += tabular.getBeginningOfTextInCell(idx);
4265         x += ADD_TO_TABULAR_WIDTH;
4266         x += scx_;
4267 }
4268
4269
4270 int InsetTabular::dist(BufferView & bv, idx_type const cell, int x, int y) const
4271 {
4272         int xx = 0;
4273         int yy = 0;
4274         Inset const & inset = *tabular.cellInset(cell);
4275         Point o = bv.coordCache().getInsets().xy(&inset);
4276         int const xbeg = o.x_ - tabular.getBeginningOfTextInCell(cell);
4277         int const xend = xbeg + tabular.columnWidth(cell);
4278         row_type const row = tabular.cellRow(cell);
4279         int const ybeg = o.y_ - tabular.rowAscent(row) -
4280                          tabular.getAdditionalHeight(row);
4281         int const yend = o.y_ + tabular.rowDescent(row);
4282
4283         if (x < xbeg)
4284                 xx = xbeg - x;
4285         else if (x > xend)
4286                 xx = x - xend;
4287
4288         if (y < ybeg)
4289                 yy = ybeg - y;
4290         else if (y > yend)
4291                 yy = y - yend;
4292
4293         //lyxerr << " xbeg=" << xbeg << "  xend=" << xend
4294         //       << " ybeg=" << ybeg << " yend=" << yend
4295         //       << " xx=" << xx << " yy=" << yy
4296         //       << " dist=" << xx + yy << endl;
4297         return xx + yy;
4298 }
4299
4300
4301 Inset * InsetTabular::editXY(Cursor & cur, int x, int y)
4302 {
4303         //lyxerr << "InsetTabular::editXY: " << this << endl;
4304         cur.setSelection(false);
4305         cur.push(*this);
4306         cur.idx() = getNearestCell(cur.bv(), x, y);
4307         resetPos(cur);
4308         return cur.bv().textMetrics(&cell(cur.idx())->text()).editXY(cur, x, y);
4309 }
4310
4311
4312 void InsetTabular::setCursorFromCoordinates(Cursor & cur, int x, int y) const
4313 {
4314         cur.idx() = getNearestCell(cur.bv(), x, y);
4315         cur.bv().textMetrics(&cell(cur.idx())->text()).setCursorFromCoordinates(cur, x, y);
4316 }
4317
4318
4319 InsetTabular::idx_type InsetTabular::getNearestCell(BufferView & bv, int x, int y) const
4320 {
4321         idx_type idx_min = 0;
4322         int dist_min = numeric_limits<int>::max();
4323         for (idx_type i = 0, n = nargs(); i != n; ++i) {
4324                 if (bv.coordCache().getInsets().has(tabular.cellInset(i).get())) {
4325                         int const d = dist(bv, i, x, y);
4326                         if (d < dist_min) {
4327                                 dist_min = d;
4328                                 idx_min = i;
4329                         }
4330                 }
4331         }
4332         return idx_min;
4333 }
4334
4335
4336 int InsetTabular::cellXPos(idx_type const cell) const
4337 {
4338         idx_type c = cell;
4339
4340         for (; !tabular.isFirstCellInRow(c); --c)
4341                 ;
4342         int lx = 0;
4343         for (; c < cell; ++c)
4344                 lx += tabular.columnWidth(c);
4345
4346         return lx;
4347 }
4348
4349
4350 void InsetTabular::resetPos(Cursor & cur) const
4351 {
4352         BufferView & bv = cur.bv();
4353         int const maxwidth = bv.workWidth();
4354
4355         int const scx_old = scx_;
4356         int const i = cur.find(this);
4357         if (i == -1) {
4358                 scx_ = 0;
4359         } else {
4360                 int const X1 = 0;
4361                 int const X2 = maxwidth;
4362                 int const offset = ADD_TO_TABULAR_WIDTH + 2;
4363                 int const x1 = xo(cur.bv()) + cellXPos(cur[i].idx()) + offset;
4364                 int const x2 = x1 + tabular.columnWidth(cur[i].idx());
4365
4366                 if (x1 < X1)
4367                         scx_ = X1 + 20 - x1;
4368                 else if (x2 > X2)
4369                         scx_ = X2 - 20 - x2;
4370                 else
4371                         scx_ = 0;
4372         }
4373
4374         // only update if offset changed
4375         if (scx_ != scx_old)
4376                 cur.updateFlags(Update::Force | Update::FitCursor);
4377 }
4378
4379
4380 void InsetTabular::moveNextCell(Cursor & cur, EntryDirection entry_from)
4381 {
4382         if (isRightToLeft(cur)) {
4383                 if (tabular.isFirstCellInRow(cur.idx())) {
4384                         row_type const row = tabular.cellRow(cur.idx());
4385                         if (row == tabular.row_info.size() - 1)
4386                                 return;
4387                         cur.idx() = tabular.cellBelow(tabular.getLastCellInRow(row));
4388                 } else {
4389                         if (cur.idx() == 0)
4390                                 return;
4391                         --cur.idx();
4392                 }
4393         } else {
4394                 if (tabular.isLastCell(cur.idx()))
4395                         return;
4396                 ++cur.idx();
4397         }
4398
4399         cur.boundary(false);
4400
4401         if (cur.selIsMultiCell()) {
4402                 cur.pit() = cur.lastpit();
4403                 cur.pos() = cur.lastpos();
4404                 resetPos(cur);
4405                 return;
4406         }
4407
4408         cur.pit() = 0;
4409         cur.pos() = 0;
4410
4411         // in visual mode, place cursor at extreme left or right
4412         
4413         switch(entry_from) {
4414
4415         case ENTRY_DIRECTION_RIGHT:
4416                 cur.posVisToRowExtremity(false /* !left */);
4417                 break;
4418         case ENTRY_DIRECTION_LEFT:
4419                 cur.posVisToRowExtremity(true /* left */);
4420                 break;
4421         case ENTRY_DIRECTION_IGNORE:
4422                 // nothing to do in this case
4423                 break;
4424
4425         }
4426
4427         resetPos(cur);
4428 }
4429
4430
4431 void InsetTabular::movePrevCell(Cursor & cur, EntryDirection entry_from)
4432 {
4433         if (isRightToLeft(cur)) {
4434                 if (tabular.isLastCellInRow(cur.idx())) {
4435                         row_type const row = tabular.cellRow(cur.idx());
4436                         if (row == 0)
4437                                 return;
4438                         cur.idx() = tabular.getFirstCellInRow(row);
4439                         cur.idx() = tabular.cellAbove(cur.idx());
4440                 } else {
4441                         if (tabular.isLastCell(cur.idx()))
4442                                 return;
4443                         ++cur.idx();
4444                 }
4445         } else {
4446                 if (cur.idx() == 0) // first cell
4447                         return;
4448                 --cur.idx();
4449         }
4450
4451         if (cur.selIsMultiCell()) {
4452                 cur.pit() = cur.lastpit();
4453                 cur.pos() = cur.lastpos();
4454                 resetPos(cur);
4455                 return;
4456         }
4457
4458         cur.pit() = cur.lastpit();
4459         cur.pos() = cur.lastpos();
4460
4461         // in visual mode, place cursor at extreme left or right
4462         
4463         switch(entry_from) {
4464
4465         case ENTRY_DIRECTION_RIGHT:
4466                 cur.posVisToRowExtremity(false /* !left */);
4467                 break;
4468         case ENTRY_DIRECTION_LEFT:
4469                 cur.posVisToRowExtremity(true /* left */);
4470                 break;
4471         case ENTRY_DIRECTION_IGNORE:
4472                 // nothing to do in this case
4473                 break;
4474
4475         }
4476
4477         resetPos(cur);
4478 }
4479
4480
4481 bool InsetTabular::tabularFeatures(Cursor & cur, string const & what)
4482 {
4483         Tabular::Feature action = Tabular::LAST_ACTION;
4484
4485         int i = 0;
4486         for (; tabularFeature[i].action != Tabular::LAST_ACTION; ++i) {
4487                 string const tmp = tabularFeature[i].feature;
4488
4489                 if (tmp == what.substr(0, tmp.length())) {
4490                         //if (!compare(tabularFeatures[i].feature.c_str(), what.c_str(),
4491                         //tabularFeatures[i].feature.length()))
4492                         action = tabularFeature[i].action;
4493                         break;
4494                 }
4495         }
4496         if (action == Tabular::LAST_ACTION)
4497                 return false;
4498
4499         string const val =
4500                 ltrim(what.substr(tabularFeature[i].feature.length()));
4501         tabularFeatures(cur, action, val);
4502         return true;
4503 }
4504
4505
4506 static void checkLongtableSpecial(Tabular::ltType & ltt,
4507                           string const & special, bool & flag)
4508 {
4509         if (special == "dl_above") {
4510                 ltt.topDL = flag;
4511                 ltt.set = false;
4512         } else if (special == "dl_below") {
4513                 ltt.bottomDL = flag;
4514                 ltt.set = false;
4515         } else if (special == "empty") {
4516                 ltt.empty = flag;
4517                 ltt.set = false;
4518         } else if (flag) {
4519                 ltt.empty = false;
4520                 ltt.set = true;
4521         }
4522 }
4523
4524 bool InsetTabular::oneCellHasRotationState(bool rotated,
4525                 row_type row_start, row_type row_end,
4526                 col_type col_start, col_type col_end) const {
4527
4528         for (row_type i = row_start; i <= row_end; ++i) {
4529                 for (col_type j = col_start; j <= col_end; ++j) {
4530                         if (tabular.getRotateCell(tabular.cellIndex(i, j))
4531                                 == rotated) {
4532                                 return true;
4533                         }
4534                 }
4535         }
4536         return false;
4537 }
4538
4539 void InsetTabular::tabularFeatures(Cursor & cur,
4540         Tabular::Feature feature, string const & value)
4541 {
4542         col_type sel_col_start;
4543         col_type sel_col_end;
4544         row_type sel_row_start;
4545         row_type sel_row_end;
4546         bool setLines = false;
4547         LyXAlignment setAlign = LYX_ALIGN_LEFT;
4548         Tabular::VAlignment setVAlign = Tabular::LYX_VALIGN_TOP;
4549
4550         switch (feature) {
4551
4552         case Tabular::M_ALIGN_LEFT:
4553         case Tabular::ALIGN_LEFT:
4554                 setAlign = LYX_ALIGN_LEFT;
4555                 break;
4556
4557         case Tabular::M_ALIGN_RIGHT:
4558         case Tabular::ALIGN_RIGHT:
4559                 setAlign = LYX_ALIGN_RIGHT;
4560                 break;
4561
4562         case Tabular::M_ALIGN_CENTER:
4563         case Tabular::ALIGN_CENTER:
4564                 setAlign = LYX_ALIGN_CENTER;
4565                 break;
4566
4567         case Tabular::ALIGN_BLOCK:
4568                 setAlign = LYX_ALIGN_BLOCK;
4569                 break;
4570
4571         case Tabular::M_VALIGN_TOP:
4572         case Tabular::VALIGN_TOP:
4573                 setVAlign = Tabular::LYX_VALIGN_TOP;
4574                 break;
4575
4576         case Tabular::M_VALIGN_BOTTOM:
4577         case Tabular::VALIGN_BOTTOM:
4578                 setVAlign = Tabular::LYX_VALIGN_BOTTOM;
4579                 break;
4580
4581         case Tabular::M_VALIGN_MIDDLE:
4582         case Tabular::VALIGN_MIDDLE:
4583                 setVAlign = Tabular::LYX_VALIGN_MIDDLE;
4584                 break;
4585
4586         default:
4587                 break;
4588         }
4589
4590         cur.recordUndoInset(ATOMIC_UNDO);
4591
4592         getSelection(cur, sel_row_start, sel_row_end, sel_col_start, sel_col_end);
4593         row_type const row = tabular.cellRow(cur.idx());
4594         col_type const column = tabular.cellColumn(cur.idx());
4595         bool flag = true;
4596         Tabular::ltType ltt;
4597
4598         switch (feature) {
4599
4600         case Tabular::SET_PWIDTH: {
4601                 Length const len(value);
4602                 tabular.setColumnPWidth(cur, cur.idx(), len);
4603                 if (len.zero()
4604                     && tabular.getAlignment(cur.idx(), true) == LYX_ALIGN_BLOCK)
4605                         tabularFeatures(cur, Tabular::ALIGN_CENTER, string());
4606                 break;
4607         }
4608
4609         case Tabular::SET_MPWIDTH:
4610                 tabular.setMColumnPWidth(cur, cur.idx(), Length(value));
4611                 break;
4612
4613         case Tabular::SET_SPECIAL_COLUMN:
4614         case Tabular::SET_SPECIAL_MULTI:
4615                 tabular.setAlignSpecial(cur.idx(), from_utf8(value), feature);
4616                 break;
4617
4618         case Tabular::APPEND_ROW:
4619                 // append the row into the tabular
4620                 tabular.appendRow(cur.idx());
4621                 break;
4622
4623         case Tabular::APPEND_COLUMN:
4624                 // append the column into the tabular
4625                 tabular.appendColumn(cur.idx());
4626                 cur.idx() = tabular.cellIndex(row, column);
4627                 break;
4628
4629         case Tabular::DELETE_ROW:
4630                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4631                         tabular.deleteRow(sel_row_start);
4632                 if (sel_row_start >= tabular.row_info.size())
4633                         --sel_row_start;
4634                 cur.idx() = tabular.cellIndex(sel_row_start, column);
4635                 cur.pit() = 0;
4636                 cur.pos() = 0;
4637                 cur.setSelection(false);
4638                 break;
4639
4640         case Tabular::DELETE_COLUMN:
4641                 for (col_type i = sel_col_start; i <= sel_col_end; ++i)
4642                         tabular.deleteColumn(sel_col_start);
4643                 if (sel_col_start >= tabular.column_info.size())
4644                         --sel_col_start;
4645                 cur.idx() = tabular.cellIndex(row, sel_col_start);
4646                 cur.pit() = 0;
4647                 cur.pos() = 0;
4648                 cur.setSelection(false);
4649                 break;
4650
4651         case Tabular::COPY_ROW:
4652                 tabular.copyRow(row);
4653                 break;
4654
4655         case Tabular::COPY_COLUMN:
4656                 tabular.copyColumn(column);
4657                 cur.idx() = tabular.cellIndex(row, column);
4658                 break;
4659
4660         case Tabular::TOGGLE_LINE_TOP: {
4661                 bool lineSet = !tabular.topLine(cur.idx());
4662                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4663                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
4664                                 tabular.setTopLine(tabular.cellIndex(i, j), lineSet);
4665                 break;
4666         }
4667
4668         case Tabular::TOGGLE_LINE_BOTTOM: {
4669                 bool lineSet = !tabular.bottomLine(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.setBottomLine(tabular.cellIndex(i, j), lineSet);
4673                 break;
4674         }
4675
4676         case Tabular::TOGGLE_LINE_LEFT: {
4677                 bool lineSet = !tabular.leftLine(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.setLeftLine(tabular.cellIndex(i, j), lineSet);
4681                 break;
4682         }
4683
4684         case Tabular::TOGGLE_LINE_RIGHT: {
4685                 bool lineSet = !tabular.rightLine(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.setRightLine(tabular.cellIndex(i, j), lineSet);
4689                 break;
4690         }
4691
4692         case Tabular::M_ALIGN_LEFT:
4693         case Tabular::M_ALIGN_RIGHT:
4694         case Tabular::M_ALIGN_CENTER:
4695                 flag = false;
4696         case Tabular::ALIGN_LEFT:
4697         case Tabular::ALIGN_RIGHT:
4698         case Tabular::ALIGN_CENTER:
4699         case Tabular::ALIGN_BLOCK:
4700                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4701                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
4702                                 tabular.setAlignment(tabular.cellIndex(i, j), setAlign, flag);
4703                 break;
4704
4705         case Tabular::M_VALIGN_TOP:
4706         case Tabular::M_VALIGN_BOTTOM:
4707         case Tabular::M_VALIGN_MIDDLE:
4708                 flag = false;
4709         case Tabular::VALIGN_TOP:
4710         case Tabular::VALIGN_BOTTOM:
4711         case Tabular::VALIGN_MIDDLE:
4712                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4713                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
4714                                 tabular.setVAlignment(tabular.cellIndex(i, j), setVAlign, flag);
4715                 break;
4716
4717         case Tabular::MULTICOLUMN: {
4718                 if (!cur.selection()) {
4719                         // just multicol for one single cell
4720                         // check whether we are completely in a multicol
4721                         if (tabular.isMultiColumn(cur.idx()))
4722                                 tabular.unsetMultiColumn(cur.idx());
4723                         else
4724                                 tabular.setMultiColumn(cur.idx(), 1);
4725                         break;
4726                 }
4727                 // we have a selection so this means we just add all this
4728                 // cells to form a multicolumn cell
4729                 idx_type const s_start = cur.selBegin().idx();
4730                 idx_type const s_end = cur.selEnd().idx();
4731                 tabular.setMultiColumn(s_start, s_end - s_start + 1);
4732                 cur.idx() = s_start;
4733                 cur.pit() = 0;
4734                 cur.pos() = 0;
4735                 cur.setSelection(false);
4736                 break;
4737         }
4738
4739         case Tabular::SET_ALL_LINES:
4740                 setLines = true;
4741         case Tabular::UNSET_ALL_LINES:
4742                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4743                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
4744                                 tabular.setAllLines(
4745                                         tabular.cellIndex(i,j), setLines);
4746                 break;
4747
4748         case Tabular::SET_BORDER_LINES:
4749                 for (row_type i = sel_row_start; i <= sel_row_end; ++i) {
4750                         tabular.setLeftLine(tabular.cellIndex(i, sel_col_start), true);
4751                         tabular.setRightLine(tabular.cellIndex(i, sel_col_end), true);
4752                 }
4753                 for (col_type j = sel_col_start; j <= sel_col_end; ++j) {
4754                         tabular.setTopLine(tabular.cellIndex(sel_row_start, j), true);
4755                         tabular.setBottomLine(tabular.cellIndex(sel_row_end, j), true);
4756                 }
4757                 break;
4758
4759         case Tabular::SET_LONGTABULAR:
4760                 tabular.is_long_tabular = true;
4761                 break;
4762
4763         case Tabular::UNSET_LONGTABULAR:
4764                 for (row_type i = 0; i < tabular.row_info.size(); ++i) {
4765                         if (tabular.ltCaption(i)) {
4766                                 cur.idx() = tabular.cellIndex(i, 0);
4767                                 cur.pit() = 0;
4768                                 cur.pos() = 0;
4769                                 tabularFeatures(cur, Tabular::TOGGLE_LTCAPTION);
4770                         }
4771                 }
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 const set = !tabular.ltCaption(row);
4886                 cur.idx() = tabular.setLTCaption(row, set);
4887                 cur.pit() = 0;
4888                 cur.pos() = 0;
4889                 cur.setSelection(false);
4890
4891                 if (set) {
4892                         // When a row is set as caption, then also insert
4893                         // a caption. Otherwise the LaTeX output is broken.
4894                         lyx::dispatch(FuncRequest(LFUN_INSET_SELECT_ALL));
4895                         lyx::dispatch(FuncRequest(LFUN_CAPTION_INSERT));
4896                 } else {
4897                         FuncRequest fr(LFUN_INSET_DISSOLVE, "caption");
4898                         if (lyx::getStatus(fr).enabled())
4899                                 lyx::dispatch(fr);
4900                 }
4901                 break;
4902         }
4903
4904         case Tabular::SET_BOOKTABS:
4905                 tabular.use_booktabs = true;
4906                 break;
4907
4908         case Tabular::UNSET_BOOKTABS:
4909                 tabular.use_booktabs = false;
4910                 break;
4911
4912         case Tabular::SET_TOP_SPACE: {
4913                 Length len;
4914                 if (value == "default")
4915                         for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4916                                 tabular.row_info[i].top_space_default = true;
4917                 else if (isValidLength(value, &len))
4918                         for (row_type i = sel_row_start; i <= sel_row_end; ++i) {
4919                                 tabular.row_info[i].top_space_default = false;
4920                                 tabular.row_info[i].top_space = len;
4921                         }
4922                 else
4923                         for (row_type i = sel_row_start; i <= sel_row_end; ++i) {
4924                                 tabular.row_info[i].top_space_default = false;
4925                                 tabular.row_info[i].top_space = len;
4926                         }
4927                 break;
4928         }
4929
4930         case Tabular::SET_BOTTOM_SPACE: {
4931                 Length len;
4932                 if (value == "default")
4933                         for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4934                                 tabular.row_info[i].bottom_space_default = true;
4935                 else if (isValidLength(value, &len))
4936                         for (row_type i = sel_row_start; i <= sel_row_end; ++i) {
4937                                 tabular.row_info[i].bottom_space_default = false;
4938                                 tabular.row_info[i].bottom_space = len;
4939                         }
4940                 else
4941                         for (row_type i = sel_row_start; i <= sel_row_end; ++i) {
4942                                 tabular.row_info[i].bottom_space_default = false;
4943                                 tabular.row_info[i].bottom_space = len;
4944                         }
4945                 break;
4946         }
4947
4948         case Tabular::SET_INTERLINE_SPACE: {
4949                 Length len;
4950                 if (value == "default")
4951                         for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4952                                 tabular.row_info[i].interline_space_default = true;
4953                 else if (isValidLength(value, &len))
4954                         for (row_type i = sel_row_start; i <= sel_row_end; ++i) {
4955                                 tabular.row_info[i].interline_space_default = false;
4956                                 tabular.row_info[i].interline_space = len;
4957                         }
4958                 else
4959                         for (row_type i = sel_row_start; i <= sel_row_end; ++i) {
4960                                 tabular.row_info[i].interline_space_default = false;
4961                                 tabular.row_info[i].interline_space = len;
4962                         }
4963                 break;
4964         }
4965
4966         // dummy stuff just to avoid warnings
4967         case Tabular::LAST_ACTION:
4968                 break;
4969         }
4970 }
4971
4972
4973 bool InsetTabular::showInsetDialog(BufferView * bv) const
4974 {
4975         bv->showDialog("tabular", params2string(*this),
4976                 const_cast<InsetTabular *>(this));
4977         return true;
4978 }
4979
4980
4981 void InsetTabular::openLayoutDialog(BufferView * bv) const
4982 {
4983         bv->showDialog("tabular", params2string(*this),
4984                 const_cast<InsetTabular *>(this));
4985 }
4986
4987
4988 bool InsetTabular::copySelection(Cursor & cur)
4989 {
4990         if (!cur.selection())
4991                 return false;
4992
4993         row_type rs, re;
4994         col_type cs, ce;
4995         getSelection(cur, rs, re, cs, ce);
4996
4997         paste_tabular.reset(new Tabular(tabular));
4998
4999         for (row_type i = 0; i < rs; ++i)
5000                 paste_tabular->deleteRow(0);
5001
5002         row_type const rows = re - rs + 1;
5003         while (paste_tabular->row_info.size() > rows)
5004                 paste_tabular->deleteRow(rows);
5005
5006         for (col_type i = 0; i < cs; ++i)
5007                 paste_tabular->deleteColumn(0);
5008
5009         col_type const columns = ce - cs + 1;
5010         while (paste_tabular->column_info.size() > columns)
5011                 paste_tabular->deleteColumn(columns);
5012
5013         paste_tabular->setBuffer(tabular.buffer());
5014
5015         odocstringstream os;
5016         OutputParams const runparams(0);
5017         paste_tabular->plaintext(os, runparams, 0, true, '\t');
5018         // Needed for the "Edit->Paste recent" menu and the system clipboard.
5019         cap::copySelection(cur, os.str());
5020
5021         // mark tabular stack dirty
5022         // FIXME: this is a workaround for bug 1919. Should be removed for 1.5,
5023         // when we (hopefully) have a one-for-all paste mechanism.
5024         // This must be called after cap::copySelection.
5025         dirtyTabularStack(true);
5026
5027         return true;
5028 }
5029
5030
5031 bool InsetTabular::pasteClipboard(Cursor & cur)
5032 {
5033         if (!paste_tabular)
5034                 return false;
5035         col_type actcol = tabular.cellColumn(cur.idx());
5036         row_type actrow = tabular.cellRow(cur.idx());
5037
5038         if (cur.selIsMultiCell()) {
5039                 row_type re;
5040                 col_type ce;
5041                 getSelection(cur, actrow, re, actcol, ce);
5042         }
5043
5044         for (row_type r1 = 0, r2 = actrow;
5045              r1 < paste_tabular->row_info.size() && r2 < tabular.row_info.size();
5046              ++r1, ++r2) {
5047                 for (col_type c1 = 0, c2 = actcol;
5048                     c1 < paste_tabular->column_info.size() && c2 < tabular.column_info.size();
5049                     ++c1, ++c2) {
5050                         if (paste_tabular->isPartOfMultiColumn(r1, c1) &&
5051                               tabular.isPartOfMultiColumn(r2, c2))
5052                                 continue;
5053                         if (paste_tabular->isPartOfMultiColumn(r1, c1)) {
5054                                 --c2;
5055                                 continue;
5056                         }
5057                         if (tabular.isPartOfMultiColumn(r2, c2)) {
5058                                 --c1;
5059                                 continue;
5060                         }
5061                         shared_ptr<InsetTableCell> inset(
5062                                 new InsetTableCell(*paste_tabular->cellInset(r1, c1)));
5063                         tabular.setCellInset(r2, c2, inset);
5064                         // FIXME: change tracking (MG)
5065                         inset->setChange(Change(buffer().params().trackChanges ?
5066                                                 Change::INSERTED : Change::UNCHANGED));
5067                         cur.pos() = 0;
5068                 }
5069         }
5070         return true;
5071 }
5072
5073
5074 void InsetTabular::cutSelection(Cursor & cur)
5075 {
5076         if (!cur.selection())
5077                 return;
5078
5079         row_type rs, re;
5080         col_type cs, ce;
5081         getSelection(cur, rs, re, cs, ce);
5082         for (row_type i = rs; i <= re; ++i) {
5083                 for (col_type j = cs; j <= ce; ++j) {
5084                         shared_ptr<InsetTableCell> t
5085                                 = cell(tabular.cellIndex(i, j));
5086                         if (buffer().params().trackChanges)
5087                                 // FIXME: Change tracking (MG)
5088                                 t->setChange(Change(Change::DELETED));
5089                         else
5090                                 t->clear();
5091                 }
5092         }
5093
5094         // cursor position might be invalid now
5095         if (cur.pit() > cur.lastpit())
5096                 cur.pit() = cur.lastpit();
5097         if (cur.pos() > cur.lastpos())
5098                 cur.pos() = cur.lastpos();
5099         cur.clearSelection();
5100 }
5101
5102
5103 bool InsetTabular::isRightToLeft(Cursor & cur) const
5104 {
5105         LASSERT(cur.depth() > 1, /**/);
5106         Paragraph const & parentpar = cur[cur.depth() - 2].paragraph();
5107         pos_type const parentpos = cur[cur.depth() - 2].pos();
5108         return parentpar.getFontSettings(buffer().params(),
5109                                          parentpos).language()->rightToLeft();
5110 }
5111
5112 docstring InsetTabular::asString(idx_type stidx, idx_type enidx, 
5113                                  bool intoInsets)
5114 {
5115         LASSERT(stidx <= enidx, return docstring());
5116         docstring retval;
5117         col_type const col1 = tabular.cellColumn(stidx);
5118         col_type const col2 = tabular.cellColumn(enidx);
5119         row_type const row1 = tabular.cellRow(stidx);
5120         row_type const row2 = tabular.cellRow(enidx);
5121         bool first = true;
5122         for (col_type col = col1; col <= col2; col++)
5123                 for (row_type row = row1; row <= row2; row++) {
5124                         if (!first)
5125                                 retval += "\n";
5126                         else
5127                                 first = false;
5128                         retval += tabular.cellInset(row, col)->asString(intoInsets);
5129                 }
5130         return retval;
5131 }
5132
5133
5134 void InsetTabular::getSelection(Cursor & cur,
5135         row_type & rs, row_type & re, col_type & cs, col_type & ce) const
5136 {
5137         CursorSlice const & beg = cur.selBegin();
5138         CursorSlice const & end = cur.selEnd();
5139         cs = tabular.cellColumn(beg.idx());
5140         ce = tabular.cellColumn(end.idx());
5141         if (cs > ce) {
5142                 ce = cs;
5143                 cs = tabular.cellColumn(end.idx());
5144         } else {
5145                 ce = tabular.cellRightColumn(end.idx());
5146         }
5147
5148         rs = tabular.cellRow(beg.idx());
5149         re = tabular.cellRow(end.idx());
5150         if (rs > re)
5151                 swap(rs, re);
5152 }
5153
5154
5155 Text * InsetTabular::getText(int idx) const
5156 {
5157         return size_t(idx) < nargs() ? cell(idx)->getText(0) : 0;
5158 }
5159
5160
5161 void InsetTabular::setChange(Change const & change)
5162 {
5163         for (idx_type idx = 0; idx < nargs(); ++idx)
5164                 cell(idx)->setChange(change);
5165 }
5166
5167
5168 void InsetTabular::acceptChanges()
5169 {
5170         for (idx_type idx = 0; idx < nargs(); ++idx)
5171                 cell(idx)->acceptChanges();
5172 }
5173
5174
5175 void InsetTabular::rejectChanges()
5176 {
5177         for (idx_type idx = 0; idx < nargs(); ++idx)
5178                 cell(idx)->rejectChanges();
5179 }
5180
5181
5182 bool InsetTabular::allowParagraphCustomization(idx_type cell) const
5183 {
5184         return tabular.getPWidth(cell).zero();
5185 }
5186
5187
5188 bool InsetTabular::forcePlainLayout(idx_type cell) const
5189 {
5190         return !tabular.getPWidth(cell).zero();
5191 }
5192
5193
5194 bool InsetTabular::insertPlaintextString(BufferView & bv, docstring const & buf,
5195                                      bool usePaste)
5196 {
5197         if (buf.length() <= 0)
5198                 return true;
5199
5200         col_type cols = 1;
5201         row_type rows = 1;
5202         col_type maxCols = 1;
5203         size_t const len = buf.length();
5204         size_t p = 0;
5205
5206         while (p < len &&
5207                (p = buf.find_first_of(from_ascii("\t\n"), p)) != docstring::npos) {
5208                 switch (buf[p]) {
5209                 case '\t':
5210                         ++cols;
5211                         break;
5212                 case '\n':
5213                         if (p + 1 < len)
5214                                 ++rows;
5215                         maxCols = max(cols, maxCols);
5216                         cols = 1;
5217                         break;
5218                 }
5219                 ++p;
5220         }
5221         maxCols = max(cols, maxCols);
5222         Tabular * loctab;
5223         idx_type cell = 0;
5224         col_type ocol = 0;
5225         row_type row = 0;
5226         if (usePaste) {
5227                 paste_tabular.reset(new Tabular(buffer_, rows, maxCols));
5228                 loctab = paste_tabular.get();
5229                 cols = 0;
5230                 dirtyTabularStack(true);
5231         } else {
5232                 loctab = &tabular;
5233                 cell = bv.cursor().idx();
5234                 ocol = tabular.cellColumn(cell);
5235                 row = tabular.cellRow(cell);
5236         }
5237
5238         size_t op = 0;
5239         idx_type const cells = loctab->numberofcells;
5240         p = 0;
5241         cols = ocol;
5242         rows = loctab->row_info.size();
5243         col_type const columns = loctab->column_info.size();
5244
5245         while (cell < cells && p < len && row < rows &&
5246                (p = buf.find_first_of(from_ascii("\t\n"), p)) != docstring::npos)
5247         {
5248                 if (p >= len)
5249                         break;
5250                 switch (buf[p]) {
5251                 case '\t':
5252                         // we can only set this if we are not too far right
5253                         if (cols < columns) {
5254                                 shared_ptr<InsetTableCell> inset = loctab->cellInset(cell);
5255                                 Font const font = bv.textMetrics(&inset->text()).
5256                                         displayFont(0, 0);
5257                                 inset->setText(buf.substr(op, p - op), font,
5258                                                buffer().params().trackChanges);
5259                                 ++cols;
5260                                 ++cell;
5261                         }
5262                         break;
5263                 case '\n':
5264                         // we can only set this if we are not too far right
5265                         if (cols < columns) {
5266                                 shared_ptr<InsetTableCell> inset = tabular.cellInset(cell);
5267                                 Font const font = bv.textMetrics(&inset->text()).
5268                                         displayFont(0, 0);
5269                                 inset->setText(buf.substr(op, p - op), font,
5270                                                buffer().params().trackChanges);
5271                         }
5272                         cols = ocol;
5273                         ++row;
5274                         if (row < rows)
5275                                 cell = loctab->cellIndex(row, cols);
5276                         break;
5277                 }
5278                 ++p;
5279                 op = p;
5280         }
5281         // check for the last cell if there is no trailing '\n'
5282         if (cell < cells && op < len) {
5283                 shared_ptr<InsetTableCell> inset = loctab->cellInset(cell);
5284                 Font const font = bv.textMetrics(&inset->text()).displayFont(0, 0);
5285                 inset->setText(buf.substr(op, len - op), font,
5286                         buffer().params().trackChanges);
5287         }
5288         return true;
5289 }
5290
5291
5292 void InsetTabular::addPreview(PreviewLoader & loader) const
5293 {
5294         row_type const rows = tabular.row_info.size();
5295         col_type const columns = tabular.column_info.size();
5296         for (row_type i = 0; i < rows; ++i) {
5297                 for (col_type j = 0; j < columns; ++j)
5298                         tabular.cellInset(i, j)->addPreview(loader);
5299         }
5300 }
5301
5302
5303 bool InsetTabular::completionSupported(Cursor const & cur) const
5304 {
5305         Cursor const & bvCur = cur.bv().cursor();
5306         if (&bvCur.inset() != this)
5307                 return false;
5308         return cur.text()->completionSupported(cur);
5309 }
5310
5311
5312 bool InsetTabular::inlineCompletionSupported(Cursor const & cur) const
5313 {
5314         return completionSupported(cur);
5315 }
5316
5317
5318 bool InsetTabular::automaticInlineCompletion() const
5319 {
5320         return lyxrc.completion_inline_text;
5321 }
5322
5323
5324 bool InsetTabular::automaticPopupCompletion() const
5325 {
5326         return lyxrc.completion_popup_text;
5327 }
5328
5329
5330 bool InsetTabular::showCompletionCursor() const
5331 {
5332         return lyxrc.completion_cursor_text;
5333 }
5334
5335
5336 CompletionList const * InsetTabular::createCompletionList(Cursor const & cur) const
5337 {
5338         return completionSupported(cur) ? cur.text()->createCompletionList(cur) : 0;
5339 }
5340
5341
5342 docstring InsetTabular::completionPrefix(Cursor const & cur) const
5343 {
5344         if (!completionSupported(cur))
5345                 return docstring();
5346         return cur.text()->completionPrefix(cur);
5347 }
5348
5349
5350 bool InsetTabular::insertCompletion(Cursor & cur, docstring const & s, bool finished)
5351 {
5352         if (!completionSupported(cur))
5353                 return false;
5354
5355         return cur.text()->insertCompletion(cur, s, finished);
5356 }
5357
5358
5359 void InsetTabular::completionPosAndDim(Cursor const & cur, int & x, int & y, 
5360                                     Dimension & dim) const
5361 {
5362         TextMetrics const & tm = cur.bv().textMetrics(cur.text());
5363         tm.completionPosAndDim(cur, x, y, dim);
5364 }
5365
5366
5367 void InsetTabular::string2params(string const & in, InsetTabular & inset)
5368 {
5369         istringstream data(in);
5370         Lexer lex;
5371         lex.setStream(data);
5372
5373         if (in.empty())
5374                 return;
5375
5376         string token;
5377         lex >> token;
5378         if (!lex || token != "tabular") {
5379                 LYXERR0("Expected arg 1 to be \"tabular\" in " << in);
5380                 return;
5381         }
5382
5383         // This is part of the inset proper that is usually swallowed
5384         // by Buffer::readInset
5385         lex >> token;
5386         if (!lex || token != "Tabular") {
5387                 LYXERR0("Expected arg 2 to be \"Tabular\" in " << in);
5388                 return;
5389         }
5390
5391         inset.read(lex);
5392 }
5393
5394
5395 string InsetTabular::params2string(InsetTabular const & inset)
5396 {
5397         ostringstream data;
5398         data << "tabular" << ' ';
5399         inset.write(data);
5400         data << "\\end_inset\n";
5401         return data.str();
5402 }
5403
5404
5405 } // namespace lyx