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