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