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