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