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