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