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