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