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