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