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