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