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