]> git.lyx.org Git - features.git/blob - src/insets/InsetTabular.cpp
* BufferView: Make use of ScreenUpdateStrategy::NoScreenUpdate, avoid a screen redraw...
[features.git] / src / insets / InsetTabular.cpp
1 /**
2  * \file InsetTabular.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Jürgen Vigna
7  * \author Lars Gullik Bjønnes
8  * \author Matthias Ettrich
9  * \author José Matos
10  * \author Jean-Marc Lasgouttes
11  * \author Angus Leeming
12  * \author John Levon
13  * \author André Pönitz
14  * \author Jürgen Vigna
15  *
16  * Full author contact details are available in file CREDITS.
17  */
18
19 #include <config.h>
20
21 #include "InsetTabular.h"
22
23 #include "buffer_funcs.h"
24 #include "Buffer.h"
25 #include "BufferParams.h"
26 #include "BufferView.h"
27 #include "CoordCache.h"
28 #include "Counters.h"
29 #include "Cursor.h"
30 #include "CutAndPaste.h"
31 #include "debug.h"
32 #include "DispatchResult.h"
33 #include "FuncRequest.h"
34 #include "FuncStatus.h"
35 #include "gettext.h"
36 #include "Language.h"
37 #include "LaTeXFeatures.h"
38 #include "Lexer.h"
39 #include "LyXFunc.h"
40 #include "MetricsInfo.h"
41 #include "OutputParams.h"
42 #include "paragraph_funcs.h"
43 #include "Paragraph.h"
44 #include "ParagraphParameters.h"
45 #include "ParIterator.h"
46 #include "TextMetrics.h"
47
48 #include "support/convert.h"
49 #include "support/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         bool const original_drawing_state = pi.pain.isDrawingEnabled();
3017
3018         idx_type idx = 0;
3019         first_visible_cell = Tabular::npos;
3020         for (row_type i = 0; i < tabular.rowCount(); ++i) {
3021                 int nx = x;
3022                 int const a = tabular.rowAscent(i);
3023                 int const d = tabular.rowDescent(i);
3024                 idx = tabular.cellIndex(i, 0);
3025                 for (col_type j = 0; j < tabular.columnCount(); ++j) {
3026                         if (tabular.isPartOfMultiColumn(i, j))
3027                                 continue;
3028                         if (first_visible_cell == Tabular::npos)
3029                                 first_visible_cell = idx;
3030
3031                         int const cx = nx + tabular.getBeginningOfTextInCell(idx);
3032                         // Cache the Inset position.
3033                         bv->coordCache().insets().add(cell(idx).get(), cx, y);
3034                         if (nx + tabular.columnWidth(idx) < 0
3035                             || nx > bv->workWidth()
3036                             || y + d < 0
3037                             || y - a > bv->workHeight()) {
3038                                 pi.pain.setDrawingEnabled(false);
3039                                 cell(idx)->draw(pi, cx, y);
3040                                 drawCellLines(pi.pain, nx, y, i, idx, pi.erased_);
3041                                 pi.pain.setDrawingEnabled(original_drawing_state);
3042                         } else {
3043                                 cell(idx)->draw(pi, cx, y);
3044                                 drawCellLines(pi.pain, nx, y, i, idx, pi.erased_);
3045                         }
3046                         nx += tabular.columnWidth(idx);
3047                         ++idx;
3048                 }
3049
3050                 if (i + 1 < tabular.rowCount())
3051                         y += d + tabular.rowAscent(i + 1) +
3052                                 tabular.getAdditionalHeight(i + 1);
3053         }
3054 }
3055
3056
3057 void InsetTabular::drawSelection(PainterInfo & pi, int x, int y) const
3058 {
3059         Cursor & cur = pi.base.bv->cursor();
3060
3061         x += scx_ + ADD_TO_TABULAR_WIDTH;
3062
3063         // FIXME: it is wrong to completely paint the background
3064         // if we want to do single row painting.
3065
3066         // Paint background of current tabular
3067         int const w = tabular.width();
3068         int const h = tabular.height();
3069         int yy = y - tabular.rowAscent(0);
3070         pi.pain.fillRectangle(x, yy, w, h, backgroundColor());
3071
3072         if (!cur.selection())
3073                 return;
3074         if (&cur.inset() != this)
3075                 return;
3076
3077         //resetPos(cur);
3078
3079
3080         if (tablemode(cur)) {
3081                 row_type rs, re;
3082                 col_type cs, ce;
3083                 getSelection(cur, rs, re, cs, ce);
3084                 y -= tabular.rowAscent(0);
3085                 for (row_type j = 0; j < tabular.rowCount(); ++j) {
3086                         int const a = tabular.rowAscent(j);
3087                         int const h = a + tabular.rowDescent(j);
3088                         int xx = x;
3089                         y += tabular.getAdditionalHeight(j);
3090                         for (col_type i = 0; i < tabular.columnCount(); ++i) {
3091                                 if (tabular.isPartOfMultiColumn(j, i))
3092                                         continue;
3093                                 idx_type const cell =
3094                                         tabular.cellIndex(j, i);
3095                                 int const w = tabular.columnWidth(cell);
3096                                 if (i >= cs && i <= ce && j >= rs && j <= re)
3097                                         pi.pain.fillRectangle(xx, y, w, h,
3098                                                               Color_selection);
3099                                 xx += w;
3100                         }
3101                         y += h;
3102                 }
3103
3104         } else {
3105                 x += getCellXPos(cur.idx());
3106                 x += tabular.getBeginningOfTextInCell(cur.idx());
3107                 cell(cur.idx())->drawSelection(pi, x, 0 /* ignored */);
3108         }
3109 }
3110
3111
3112 void InsetTabular::drawCellLines(Painter & pain, int x, int y,
3113                                  row_type row, idx_type cell, bool erased) const
3114 {
3115         int x2 = x + tabular.columnWidth(cell);
3116         bool on_off = false;
3117         ColorCode col = Color_tabularline;
3118         ColorCode onoffcol = Color_tabularonoffline;
3119
3120         if (erased) {
3121                 col = Color_deletedtext;
3122                 onoffcol = Color_deletedtext;
3123         }
3124
3125         if (!tabular.topAlreadyDrawn(cell)) {
3126                 on_off = !tabular.topLine(cell);
3127                 pain.line(x, y - tabular.rowAscent(row),
3128                           x2, y -  tabular.rowAscent(row),
3129                           on_off ? onoffcol : col,
3130                           on_off ? Painter::line_onoffdash : Painter::line_solid);
3131         }
3132         on_off = !tabular.bottomLine(cell);
3133         pain.line(x, y + tabular.rowDescent(row),
3134                   x2, y + tabular.rowDescent(row),
3135                   on_off ? onoffcol : col,
3136                   on_off ? Painter::line_onoffdash : Painter::line_solid);
3137         if (!tabular.leftAlreadyDrawn(cell)) {
3138                 on_off = !tabular.leftLine(cell);
3139                 pain.line(x, y -  tabular.rowAscent(row),
3140                           x, y +  tabular.rowDescent(row),
3141                           on_off ? onoffcol : col,
3142                           on_off ? Painter::line_onoffdash : Painter::line_solid);
3143         }
3144         on_off = !tabular.rightLine(cell);
3145         pain.line(x2 - tabular.getAdditionalWidth(cell),
3146                   y -  tabular.rowAscent(row),
3147                   x2 - tabular.getAdditionalWidth(cell),
3148                   y +  tabular.rowDescent(row),
3149                   on_off ? onoffcol : col,
3150                   on_off ? Painter::line_onoffdash : Painter::line_solid);
3151 }
3152
3153
3154 docstring const InsetTabular::editMessage() const
3155 {
3156         return _("Opened table");
3157 }
3158
3159
3160 void InsetTabular::edit(Cursor & cur, bool left)
3161 {
3162         //lyxerr << "InsetTabular::edit: " << this << endl;
3163         cur.finishUndo();
3164         cur.selection() = false;
3165         cur.push(*this);
3166         if (left) {
3167                 if (isRightToLeft(cur))
3168                         cur.idx() = tabular.getLastCellInRow(0);
3169                 else
3170                         cur.idx() = 0;
3171                 cur.pit() = 0;
3172                 cur.pos() = 0;
3173         } else {
3174                 if (isRightToLeft(cur))
3175                         cur.idx() = tabular.getFirstCellInRow(tabular.rowCount() - 1);
3176                 else
3177                         cur.idx() = tabular.cellCount() - 1;
3178                 cur.pit() = 0;
3179                 cur.pos() = cur.lastpos(); // FIXME crude guess
3180         }
3181         // FIXME: this accesses the position cache before it is initialized
3182         //resetPos(cur);
3183         //cur.bv().fitCursor();
3184 }
3185
3186
3187 void InsetTabular::updateLabels(Buffer const & buf, ParIterator const & it)
3188 {
3189         // In a longtable, tell captions what the current float is
3190         Counters & cnts = buf.params().getTextClass().counters();
3191         string const saveflt = cnts.current_float();
3192         if (tabular.isLongTabular())
3193                 cnts.current_float("table");
3194
3195         ParIterator it2 = it;
3196         it2.forwardPos();
3197         size_t const end = it2.nargs();
3198         for ( ; it2.idx() < end; it2.top().forwardIdx())
3199                 lyx::updateLabels(buf, it2);
3200
3201         //reset afterwards
3202         if (tabular.isLongTabular())
3203                 cnts.current_float(saveflt);
3204 }
3205
3206
3207 void InsetTabular::doDispatch(Cursor & cur, FuncRequest & cmd)
3208 {
3209         LYXERR(Debug::DEBUG) << "# InsetTabular::doDispatch: cmd: " << cmd
3210                              << "\n  cur:" << cur << endl;
3211         CursorSlice sl = cur.top();
3212         Cursor & bvcur = cur.bv().cursor();
3213
3214         switch (cmd.action) {
3215
3216         case LFUN_MOUSE_PRESS:
3217                 //lyxerr << "# InsetTabular::MousePress\n" << cur.bv().cursor() << endl;
3218
3219                 // do not reset cursor/selection if we have selected
3220                 // some cells (bug 2715).
3221                 if (cmd.button() == mouse_button::button3
3222                     && &bvcur.selBegin().inset() == this 
3223                     && tablemode(bvcur)) 
3224                         ;
3225                 else
3226                         // Let InsetText do it
3227                         cell(cur.idx())->dispatch(cur, cmd);
3228                 break;
3229         case LFUN_MOUSE_MOTION:
3230                 //lyxerr << "# InsetTabular::MouseMotion\n" << bvcur << endl;
3231                 if (cmd.button() == mouse_button::button1) {
3232                         // only accept motions to places not deeper nested than the real anchor
3233                         if (bvcur.anchor_.hasPart(cur)) {
3234                                 // only update if selection changes
3235                                 if (bvcur.idx() == cur.idx() &&
3236                                         !(bvcur.anchor_.idx() == cur.idx() && bvcur.pos() != cur.pos()))
3237                                         cur.noUpdate();
3238                                 setCursorFromCoordinates(cur, cmd.x, cmd.y);
3239                                 bvcur.setCursor(cur);
3240                                 bvcur.selection() = true;
3241                         } else
3242                                 cur.undispatched();
3243                 }
3244                 break;
3245
3246         case LFUN_MOUSE_RELEASE:
3247                 //lyxerr << "# InsetTabular::MouseRelease\n" << bvcur << endl;
3248                 if (cmd.button() == mouse_button::button3)
3249                         InsetTabularMailer(*this).showDialog(&cur.bv());
3250                 break;
3251
3252         case LFUN_CELL_BACKWARD:
3253                 movePrevCell(cur);
3254                 cur.selection() = false;
3255                 break;
3256
3257         case LFUN_CELL_FORWARD:
3258                 moveNextCell(cur);
3259                 cur.selection() = false;
3260                 break;
3261
3262         case LFUN_CHAR_FORWARD_SELECT:
3263         case LFUN_CHAR_FORWARD:
3264                 cell(cur.idx())->dispatch(cur, cmd);
3265                 if (!cur.result().dispatched()) {
3266                         moveNextCell(cur);
3267                         if (sl == cur.top())
3268                                 cmd = FuncRequest(LFUN_FINISHED_FORWARD);
3269                         else
3270                                 cur.dispatched();
3271                 }
3272                 break;
3273
3274         case LFUN_CHAR_BACKWARD_SELECT:
3275         case LFUN_CHAR_BACKWARD:
3276                 cell(cur.idx())->dispatch(cur, cmd);
3277                 if (!cur.result().dispatched()) {
3278                         movePrevCell(cur);
3279                         if (sl == cur.top())
3280                                 cmd = FuncRequest(LFUN_FINISHED_BACKWARD);
3281                         else
3282                                 cur.dispatched();
3283                 }
3284                 break;
3285
3286         case LFUN_CHAR_RIGHT_SELECT:
3287         case LFUN_CHAR_RIGHT:
3288                 //FIXME: for visual cursor, really move right
3289                 if (isRightToLeft(cur))
3290                         lyx::dispatch(FuncRequest(
3291                                 cmd.action == LFUN_CHAR_RIGHT_SELECT ?
3292                                         LFUN_CHAR_BACKWARD_SELECT : LFUN_CHAR_BACKWARD));
3293                 else
3294                         lyx::dispatch(FuncRequest(
3295                                 cmd.action == LFUN_CHAR_RIGHT_SELECT ?
3296                                         LFUN_CHAR_FORWARD_SELECT : LFUN_CHAR_FORWARD));
3297                 break;
3298
3299         case LFUN_CHAR_LEFT_SELECT:
3300         case LFUN_CHAR_LEFT:
3301                 //FIXME: for visual cursor, really move left
3302                 if (isRightToLeft(cur))
3303                         lyx::dispatch(FuncRequest(
3304                                 cmd.action == LFUN_CHAR_LEFT_SELECT ?
3305                                         LFUN_CHAR_FORWARD_SELECT : LFUN_CHAR_FORWARD));
3306                 else
3307                         lyx::dispatch(FuncRequest(
3308                                 cmd.action == LFUN_CHAR_LEFT_SELECT ?
3309                                         LFUN_CHAR_BACKWARD_SELECT : LFUN_CHAR_BACKWARD));
3310                 break;
3311
3312         case LFUN_DOWN_SELECT:
3313         case LFUN_DOWN:
3314                 cell(cur.idx())->dispatch(cur, cmd);
3315                 cur.dispatched(); // override the cell's decision
3316                 if (sl == cur.top())
3317                         // if our Text didn't do anything to the cursor
3318                         // then we try to put the cursor into the cell below
3319                         // setting also the right targetX.
3320                         if (tabular.cellRow(cur.idx()) != tabular.rowCount() - 1) {
3321                                 cur.idx() = tabular.getCellBelow(cur.idx());
3322                                 cur.pit() = 0;
3323                                 TextMetrics const & tm =
3324                                         cur.bv().textMetrics(cell(cur.idx())->getText(0));
3325                                 cur.pos() = tm.x2pos(cur.pit(), 0, cur.targetX());
3326                         }
3327                 if (sl == cur.top()) {
3328                         // we trick it to go to forward after leaving the
3329                         // tabular.
3330                         cmd = FuncRequest(LFUN_FINISHED_FORWARD);
3331                         cur.undispatched();
3332                 }
3333                 break;
3334
3335         case LFUN_UP_SELECT:
3336         case LFUN_UP:
3337                 cell(cur.idx())->dispatch(cur, cmd);
3338                 cur.dispatched(); // override the cell's decision
3339                 if (sl == cur.top())
3340                         // if our Text didn't do anything to the cursor
3341                         // then we try to put the cursor into the cell above
3342                         // setting also the right targetX.
3343                         if (tabular.cellRow(cur.idx()) != 0) {
3344                                 cur.idx() = tabular.getCellAbove(cur.idx());
3345                                 cur.pit() = cur.lastpit();
3346                                 Text const * text = cell(cur.idx())->getText(0);
3347                                 TextMetrics const & tm = cur.bv().textMetrics(text);
3348                                 ParagraphMetrics const & pm =
3349                                         tm.parMetrics(cur.lastpit());
3350                                 cur.pos() = tm.x2pos(cur.pit(), pm.rows().size()-1, cur.targetX());
3351                         }
3352                 if (sl == cur.top()) {
3353                         cmd = FuncRequest(LFUN_UP);
3354                         cur.undispatched();
3355                 }
3356                 break;
3357
3358 //      case LFUN_SCREEN_DOWN: {
3359 //              //if (hasSelection())
3360 //              //      cur.selection() = false;
3361 //              col_type const col = tabular.cellColumn(cur.idx());
3362 //              int const t =   cur.bv().top_y() + cur.bv().height();
3363 //              if (t < yo() + tabular.getHeightOfTabular()) {
3364 //                      cur.bv().scrollDocView(t);
3365 //                      cur.idx() = tabular.getCellBelow(first_visible_cell) + col;
3366 //              } else {
3367 //                      cur.idx() = tabular.getFirstCellInRow(tabular.rows() - 1) + col;
3368 //              }
3369 //              cur.par() = 0;
3370 //              cur.pos() = 0;
3371 //              break;
3372 //      }
3373 //
3374 //      case LFUN_SCREEN_UP: {
3375 //              //if (hasSelection())
3376 //              //      cur.selection() = false;
3377 //              col_type const col = tabular.cellColumn(cur.idx());
3378 //              int const t =   cur.bv().top_y() + cur.bv().height();
3379 //              if (yo() < 0) {
3380 //                      cur.bv().scrollDocView(t);
3381 //                      if (yo() > 0)
3382 //                              cur.idx() = col;
3383 //                      else
3384 //                              cur.idx() = tabular.getCellBelow(first_visible_cell) + col;
3385 //              } else {
3386 //                      cur.idx() = col;
3387 //              }
3388 //              cur.par() = cur.lastpar();
3389 //              cur.pos() = cur.lastpos();
3390 //              break;
3391 //      }
3392
3393         case LFUN_LAYOUT_TABULAR:
3394                 InsetTabularMailer(*this).showDialog(&cur.bv());
3395                 break;
3396
3397         case LFUN_INSET_DIALOG_UPDATE:
3398                 InsetTabularMailer(*this).updateDialog(&cur.bv());
3399                 break;
3400
3401         case LFUN_TABULAR_FEATURE:
3402                 if (!tabularFeatures(cur, to_utf8(cmd.argument())))
3403                         cur.undispatched();
3404                 break;
3405
3406         // insert file functions
3407         case LFUN_FILE_INSERT_PLAINTEXT_PARA:
3408         case LFUN_FILE_INSERT_PLAINTEXT: {
3409                 // FIXME UNICODE
3410                 docstring const tmpstr = cur.bv().contentsOfPlaintextFile(to_utf8(cmd.argument()), false);
3411                 if (!tmpstr.empty() && !insertPlaintextString(cur.bv(), tmpstr, false))
3412                         cur.undispatched();
3413                 break;
3414         }
3415
3416         case LFUN_CUT:
3417                 if (tablemode(cur)) {
3418                         if (copySelection(cur)) {
3419                                 cur.recordUndoInset(DELETE_UNDO);
3420                                 cutSelection(cur);
3421                         }
3422                 }
3423                 else
3424                         cell(cur.idx())->dispatch(cur, cmd);
3425                 break;
3426
3427         case LFUN_CHAR_DELETE_BACKWARD:
3428         case LFUN_CHAR_DELETE_FORWARD:
3429                 if (tablemode(cur)) {
3430                         cur.recordUndoInset(DELETE_UNDO);
3431                         cutSelection(cur);
3432                 }
3433                 else
3434                         cell(cur.idx())->dispatch(cur, cmd);
3435                 break;
3436
3437         case LFUN_COPY:
3438                 if (!cur.selection())
3439                         break;
3440                 if (tablemode(cur)) {
3441                         cur.finishUndo();
3442                         copySelection(cur);
3443                 } else
3444                         cell(cur.idx())->dispatch(cur, cmd);
3445                 break;
3446
3447         case LFUN_CLIPBOARD_PASTE:
3448         case LFUN_PRIMARY_SELECTION_PASTE: {
3449                 docstring const clip = (cmd.action == LFUN_CLIPBOARD_PASTE) ?
3450                         theClipboard().getAsText() :
3451                         theSelection().get();
3452                 if (clip.empty())
3453                         break;
3454                 // pass to InsertPlaintextString, but
3455                 // only if we have multi-cell content
3456                 if (clip.find_first_of(from_ascii("\t\n")) != docstring::npos) {
3457                         if (insertPlaintextString(cur.bv(), clip, false)) {
3458                                 // content has been replaced,
3459                                 // so cursor might be invalid
3460                                 cur.pos() = cur.lastpos();
3461                                 bvcur.setCursor(cur);
3462                                 break;
3463                         }
3464                 }
3465                 // Let the cell handle normal text
3466                 cell(cur.idx())->dispatch(cur, cmd);
3467                 break;
3468         }
3469
3470         case LFUN_PASTE:
3471                 if (tabularStackDirty() && theClipboard().isInternal()) {
3472                         cur.recordUndoInset(INSERT_UNDO);
3473                         pasteClipboard(cur);
3474                         break;
3475                 }
3476                 cell(cur.idx())->dispatch(cur, cmd);
3477                 break;
3478
3479         case LFUN_FONT_EMPH:
3480         case LFUN_FONT_BOLD:
3481         case LFUN_FONT_ROMAN:
3482         case LFUN_FONT_NOUN:
3483         case LFUN_FONT_ITAL:
3484         case LFUN_FONT_FRAK:
3485         case LFUN_FONT_TYPEWRITER:
3486         case LFUN_FONT_SANS:
3487         case LFUN_FONT_FREE_APPLY:
3488         case LFUN_FONT_FREE_UPDATE:
3489         case LFUN_FONT_SIZE:
3490         case LFUN_FONT_UNDERLINE:
3491         case LFUN_LANGUAGE:
3492         case LFUN_WORD_CAPITALIZE:
3493         case LFUN_WORD_UPCASE:
3494         case LFUN_WORD_LOWCASE:
3495         case LFUN_CHARS_TRANSPOSE:
3496                 if (tablemode(cur)) {
3497                         row_type rs, re;
3498                         col_type cs, ce;
3499                         getSelection(cur, rs, re, cs, ce);
3500                         Cursor tmpcur = cur;
3501                         for (row_type i = rs; i <= re; ++i) {
3502                                 for (col_type j = cs; j <= ce; ++j) {
3503                                         // cursor follows cell:
3504                                         tmpcur.idx() = tabular.cellIndex(i, j);
3505                                         // select this cell only:
3506                                         tmpcur.pit() = 0;
3507                                         tmpcur.pos() = 0;
3508                                         tmpcur.resetAnchor();
3509                                         tmpcur.pit() = tmpcur.lastpit();
3510                                         tmpcur.pos() = tmpcur.top().lastpos();
3511                                         tmpcur.setCursor(tmpcur);
3512                                         tmpcur.setSelection();
3513                                         cell(tmpcur.idx())->dispatch(tmpcur, cmd);
3514                                 }
3515                         }
3516                         break;
3517                 } else {
3518                         cell(cur.idx())->dispatch(cur, cmd);
3519                         break;
3520                 }
3521         default:
3522                 // we try to handle this event in the insets dispatch function.
3523                 cell(cur.idx())->dispatch(cur, cmd);
3524                 break;
3525         }
3526 }
3527
3528
3529 // function sets an object as defined in func_status.h:
3530 // states OK, Unknown, Disabled, On, Off.
3531 bool InsetTabular::getStatus(Cursor & cur, FuncRequest const & cmd,
3532         FuncStatus & status) const
3533 {
3534         switch (cmd.action) {
3535         case LFUN_TABULAR_FEATURE: {
3536                 int action = Tabular::LAST_ACTION;
3537                 int i = 0;
3538                 for (; tabularFeature[i].action != Tabular::LAST_ACTION; ++i) {
3539                         string const tmp = tabularFeature[i].feature;
3540                         if (tmp == to_utf8(cmd.argument()).substr(0, tmp.length())) {
3541                                 action = tabularFeature[i].action;
3542                                 break;
3543                         }
3544                 }
3545                 if (action == Tabular::LAST_ACTION) {
3546                         status.clear();
3547                         status.unknown(true);
3548                         return true;
3549                 }
3550
3551                 string const argument
3552                         = ltrim(to_utf8(cmd.argument()).substr(tabularFeature[i].feature.length()));
3553
3554                 row_type sel_row_start = 0;
3555                 row_type sel_row_end = 0;
3556                 col_type sel_col_start = 0;
3557                 col_type sel_col_end = 0;
3558                 Tabular::ltType dummyltt;
3559                 bool flag = true;
3560
3561                 getSelection(cur, sel_row_start, sel_row_end, sel_col_start, sel_col_end);
3562
3563                 switch (action) {
3564                 case Tabular::SET_PWIDTH:
3565                 case Tabular::SET_MPWIDTH:
3566                 case Tabular::SET_SPECIAL_COLUMN:
3567                 case Tabular::SET_SPECIAL_MULTI:
3568                 case Tabular::APPEND_ROW:
3569                 case Tabular::APPEND_COLUMN:
3570                 case Tabular::DELETE_ROW:
3571                 case Tabular::DELETE_COLUMN:
3572                 case Tabular::COPY_ROW:
3573                 case Tabular::COPY_COLUMN:
3574                 case Tabular::SET_ALL_LINES:
3575                 case Tabular::UNSET_ALL_LINES:
3576                 case Tabular::SET_TOP_SPACE:
3577                 case Tabular::SET_BOTTOM_SPACE:
3578                 case Tabular::SET_INTERLINE_SPACE:
3579                         status.clear();
3580                         return true;
3581
3582                 case Tabular::MULTICOLUMN:
3583                         status.setOnOff(tabular.isMultiColumn(cur.idx()));
3584                         break;
3585
3586                 case Tabular::M_TOGGLE_LINE_TOP:
3587                         flag = false;
3588                 case Tabular::TOGGLE_LINE_TOP:
3589                         status.setOnOff(tabular.topLine(cur.idx(), flag));
3590                         break;
3591
3592                 case Tabular::M_TOGGLE_LINE_BOTTOM:
3593                         flag = false;
3594                 case Tabular::TOGGLE_LINE_BOTTOM:
3595                         status.setOnOff(tabular.bottomLine(cur.idx(), flag));
3596                         break;
3597
3598                 case Tabular::M_TOGGLE_LINE_LEFT:
3599                         flag = false;
3600                 case Tabular::TOGGLE_LINE_LEFT:
3601                         status.setOnOff(tabular.leftLine(cur.idx(), flag));
3602                         break;
3603
3604                 case Tabular::M_TOGGLE_LINE_RIGHT:
3605                         flag = false;
3606                 case Tabular::TOGGLE_LINE_RIGHT:
3607                         status.setOnOff(tabular.rightLine(cur.idx(), flag));
3608                         break;
3609
3610                 case Tabular::M_ALIGN_LEFT:
3611                         flag = false;
3612                 case Tabular::ALIGN_LEFT:
3613                         status.setOnOff(tabular.getAlignment(cur.idx(), flag) == LYX_ALIGN_LEFT);
3614                         break;
3615
3616                 case Tabular::M_ALIGN_RIGHT:
3617                         flag = false;
3618                 case Tabular::ALIGN_RIGHT:
3619                         status.setOnOff(tabular.getAlignment(cur.idx(), flag) == LYX_ALIGN_RIGHT);
3620                         break;
3621
3622                 case Tabular::M_ALIGN_CENTER:
3623                         flag = false;
3624                 case Tabular::ALIGN_CENTER:
3625                         status.setOnOff(tabular.getAlignment(cur.idx(), flag) == LYX_ALIGN_CENTER);
3626                         break;
3627
3628                 case Tabular::ALIGN_BLOCK:
3629                         status.enabled(!tabular.getPWidth(cur.idx()).zero());
3630                         status.setOnOff(tabular.getAlignment(cur.idx(), flag) == LYX_ALIGN_BLOCK);
3631                         break;
3632
3633                 case Tabular::M_VALIGN_TOP:
3634                         flag = false;
3635                 case Tabular::VALIGN_TOP:
3636                         status.setOnOff(
3637                                 tabular.getVAlignment(cur.idx(), flag) == Tabular::LYX_VALIGN_TOP);
3638                         break;
3639
3640                 case Tabular::M_VALIGN_BOTTOM:
3641                         flag = false;
3642                 case Tabular::VALIGN_BOTTOM:
3643                         status.setOnOff(
3644                                 tabular.getVAlignment(cur.idx(), flag) == Tabular::LYX_VALIGN_BOTTOM);
3645                         break;
3646
3647                 case Tabular::M_VALIGN_MIDDLE:
3648                         flag = false;
3649                 case Tabular::VALIGN_MIDDLE:
3650                         status.setOnOff(
3651                                 tabular.getVAlignment(cur.idx(), flag) == Tabular::LYX_VALIGN_MIDDLE);
3652                         break;
3653
3654                 case Tabular::SET_LONGTABULAR:
3655                         status.setOnOff(tabular.isLongTabular());
3656                         break;
3657
3658                 case Tabular::UNSET_LONGTABULAR:
3659                         status.setOnOff(!tabular.isLongTabular());
3660                         break;
3661
3662                 case Tabular::TOGGLE_ROTATE_TABULAR:
3663                 case Tabular::SET_ROTATE_TABULAR:
3664                         status.setOnOff(tabular.getRotateTabular());
3665                         break;
3666
3667                 case Tabular::UNSET_ROTATE_TABULAR:
3668                         status.setOnOff(!tabular.getRotateTabular());
3669                         break;
3670
3671                 case Tabular::TOGGLE_ROTATE_CELL:
3672                 case Tabular::SET_ROTATE_CELL:
3673                         status.setOnOff(!oneCellHasRotationState(false,
3674                                 sel_row_start, sel_row_end, sel_col_start, sel_col_end));
3675                         break;
3676
3677                 case Tabular::UNSET_ROTATE_CELL:
3678                         status.setOnOff(!oneCellHasRotationState(true,
3679                                 sel_row_start, sel_row_end, sel_col_start, sel_col_end));
3680                         break;
3681
3682                 case Tabular::SET_USEBOX:
3683                         status.setOnOff(convert<int>(argument) == tabular.getUsebox(cur.idx()));
3684                         break;
3685
3686                 case Tabular::SET_LTFIRSTHEAD:
3687                         status.setOnOff(tabular.getRowOfLTHead(sel_row_start, dummyltt));
3688                         break;
3689
3690                 case Tabular::UNSET_LTFIRSTHEAD:
3691                         status.setOnOff(!tabular.getRowOfLTHead(sel_row_start, dummyltt));
3692                         break;
3693
3694                 case Tabular::SET_LTHEAD:
3695                         status.setOnOff(tabular.getRowOfLTHead(sel_row_start, dummyltt));
3696                         break;
3697
3698                 case Tabular::UNSET_LTHEAD:
3699                         status.setOnOff(!tabular.getRowOfLTHead(sel_row_start, dummyltt));
3700                         break;
3701
3702                 case Tabular::SET_LTFOOT:
3703                         status.setOnOff(tabular.getRowOfLTFoot(sel_row_start, dummyltt));
3704                         break;
3705
3706                 case Tabular::UNSET_LTFOOT:
3707                         status.setOnOff(!tabular.getRowOfLTFoot(sel_row_start, dummyltt));
3708                         break;
3709
3710                 case Tabular::SET_LTLASTFOOT:
3711                         status.setOnOff(tabular.getRowOfLTFoot(sel_row_start, dummyltt));
3712                         break;
3713
3714                 case Tabular::UNSET_LTLASTFOOT:
3715                         status.setOnOff(!tabular.getRowOfLTFoot(sel_row_start, dummyltt));
3716                         break;
3717
3718                 case Tabular::SET_LTNEWPAGE:
3719                         status.setOnOff(tabular.getLTNewPage(sel_row_start));
3720                         break;
3721
3722                 case Tabular::SET_BOOKTABS:
3723                         status.setOnOff(tabular.useBookTabs());
3724                         break;
3725
3726                 case Tabular::UNSET_BOOKTABS:
3727                         status.setOnOff(!tabular.useBookTabs());
3728                         break;
3729
3730                 default:
3731                         status.clear();
3732                         status.enabled(false);
3733                         break;
3734                 }
3735                 return true;
3736         }
3737
3738         // These are only enabled inside tabular
3739         case LFUN_CELL_BACKWARD:
3740         case LFUN_CELL_FORWARD:
3741                 status.enabled(true);
3742                 return true;
3743
3744         // disable these with multiple cells selected
3745         case LFUN_INSET_INSERT:
3746         case LFUN_TABULAR_INSERT:
3747         case LFUN_FLEX_INSERT:
3748         case LFUN_FLOAT_INSERT:
3749         case LFUN_FLOAT_WIDE_INSERT:
3750         case LFUN_FOOTNOTE_INSERT:
3751         case LFUN_MARGINALNOTE_INSERT:
3752         case LFUN_MATH_INSERT:
3753         case LFUN_MATH_MODE:
3754         case LFUN_MATH_MUTATE:
3755         case LFUN_MATH_DISPLAY:
3756         case LFUN_NOTE_INSERT:
3757         case LFUN_OPTIONAL_INSERT:
3758         case LFUN_BOX_INSERT:
3759         case LFUN_BRANCH_INSERT:
3760         case LFUN_WRAP_INSERT:
3761         case LFUN_ERT_INSERT: {
3762                 if (tablemode(cur)) {
3763                         status.enabled(false);
3764                         return true;
3765                 } else
3766                         return cell(cur.idx())->getStatus(cur, cmd, status);
3767         }
3768
3769         // disable in non-fixed-width cells
3770         case LFUN_BREAK_LINE:
3771         case LFUN_BREAK_PARAGRAPH:
3772         case LFUN_BREAK_PARAGRAPH_SKIP: {
3773                 if (tabular.getPWidth(cur.idx()).zero()) {
3774                         status.enabled(false);
3775                         return true;
3776                 } else
3777                         return cell(cur.idx())->getStatus(cur, cmd, status);
3778         }
3779
3780         case LFUN_PASTE:
3781                 if (tabularStackDirty() && theClipboard().isInternal()) {
3782                         status.enabled(true);
3783                         return true;
3784                 } else
3785                         return cell(cur.idx())->getStatus(cur, cmd, status);
3786
3787         case LFUN_INSET_MODIFY:
3788                 if (insetCode(cmd.getArg(0)) == TABULAR_CODE) {
3789                         status.enabled(true);
3790                         return true;
3791                 }
3792                 // Fall through
3793
3794         default:
3795                 // we try to handle this event in the insets dispatch function.
3796                 return cell(cur.idx())->getStatus(cur, cmd, status);
3797         }
3798 }
3799
3800
3801 int InsetTabular::latex(Buffer const & buf, odocstream & os,
3802                         OutputParams const & runparams) const
3803 {
3804         return tabular.latex(buf, os, runparams);
3805 }
3806
3807
3808 int InsetTabular::plaintext(Buffer const & buf, odocstream & os,
3809                             OutputParams const & runparams) const
3810 {
3811         os << '\n'; // output table on a new line
3812         int const dp = runparams.linelen > 0 ? runparams.depth : 0;
3813         tabular.plaintext(buf, os, runparams, dp, false, 0);
3814         return PLAINTEXT_NEWLINE;
3815 }
3816
3817
3818 int InsetTabular::docbook(Buffer const & buf, odocstream & os,
3819                           OutputParams const & runparams) const
3820 {
3821         int ret = 0;
3822         Inset * master = 0;
3823
3824         // FIXME: Why not pass a proper DocIterator here?
3825 #if 0
3826         // if the table is inside a float it doesn't need the informaltable
3827         // wrapper. Search for it.
3828         for (master = owner(); master; master = master->owner())
3829                 if (master->lyxCode() == FLOAT_CODE)
3830                         break;
3831 #endif
3832
3833         if (!master) {
3834                 os << "<informaltable>";
3835                 ++ret;
3836         }
3837         ret += tabular.docbook(buf, os, runparams);
3838         if (!master) {
3839                 os << "</informaltable>";
3840                 ++ret;
3841         }
3842         return ret;
3843 }
3844
3845
3846 void InsetTabular::validate(LaTeXFeatures & features) const
3847 {
3848         tabular.validate(features);
3849 }
3850
3851
3852 shared_ptr<InsetText const> InsetTabular::cell(idx_type idx) const
3853 {
3854         return tabular.getCellInset(idx);
3855 }
3856
3857
3858 shared_ptr<InsetText> InsetTabular::cell(idx_type idx)
3859 {
3860         return tabular.getCellInset(idx);
3861 }
3862
3863
3864 void InsetTabular::cursorPos(BufferView const & bv,
3865                 CursorSlice const & sl, bool boundary, int & x, int & y) const
3866 {
3867         cell(sl.idx())->cursorPos(bv, sl, boundary, x, y);
3868
3869         // y offset     correction
3870         int const row = tabular.cellRow(sl.idx());
3871         for (int i = 0; i <= row; ++i) {
3872                 if (i != 0) {
3873                         y += tabular.rowAscent(i);
3874                         y += tabular.getAdditionalHeight(i);
3875                 }
3876                 if (i != row)
3877                         y += tabular.rowDescent(i);
3878         }
3879
3880         // x offset correction
3881         int const col = tabular.cellColumn(sl.idx());
3882         int idx = tabular.cellIndex(row, 0);
3883         for (int j = 0; j < col; ++j) {
3884                 if (tabular.isPartOfMultiColumn(row, j))
3885                         continue;
3886                 x += tabular.columnWidth(idx);
3887                 ++idx;
3888         }
3889         x += tabular.getBeginningOfTextInCell(idx);
3890         x += ADD_TO_TABULAR_WIDTH;
3891         x += scx_;
3892 }
3893
3894
3895 int InsetTabular::dist(BufferView & bv, idx_type const cell, int x, int y) const
3896 {
3897         int xx = 0;
3898         int yy = 0;
3899         Inset const & inset = *tabular.getCellInset(cell);
3900         Point o = bv.coordCache().getInsets().xy(&inset);
3901         int const xbeg = o.x_ - tabular.getBeginningOfTextInCell(cell);
3902         int const xend = xbeg + tabular.columnWidth(cell);
3903         row_type const row = tabular.cellRow(cell);
3904         int const ybeg = o.y_ - tabular.rowAscent(row) -
3905                          tabular.getAdditionalHeight(row);
3906         int const yend = o.y_ + tabular.rowDescent(row);
3907
3908         if (x < xbeg)
3909                 xx = xbeg - x;
3910         else if (x > xend)
3911                 xx = x - xend;
3912
3913         if (y < ybeg)
3914                 yy = ybeg - y;
3915         else if (y > yend)
3916                 yy = y - yend;
3917
3918         //lyxerr << " xbeg=" << xbeg << "  xend=" << xend
3919         //       << " ybeg=" << ybeg << " yend=" << yend
3920         //       << " xx=" << xx << " yy=" << yy
3921         //       << " dist=" << xx + yy << endl;
3922         return xx + yy;
3923 }
3924
3925
3926 Inset * InsetTabular::editXY(Cursor & cur, int x, int y)
3927 {
3928         //lyxerr << "InsetTabular::editXY: " << this << endl;
3929         cur.selection() = false;
3930         cur.push(*this);
3931         cur.idx() = getNearestCell(cur.bv(), x, y);
3932         resetPos(cur);
3933         return cur.bv().textMetrics(&cell(cur.idx())->text_).editXY(cur, x, y);
3934 }
3935
3936
3937 void InsetTabular::setCursorFromCoordinates(Cursor & cur, int x, int y) const
3938 {
3939         cur.idx() = getNearestCell(cur.bv(), x, y);
3940         cur.bv().textMetrics(&cell(cur.idx())->text_).setCursorFromCoordinates(cur, x, y);
3941 }
3942
3943
3944 InsetTabular::idx_type InsetTabular::getNearestCell(BufferView & bv, int x, int y) const
3945 {
3946         idx_type idx_min = 0;
3947         int dist_min = std::numeric_limits<int>::max();
3948         for (idx_type i = 0, n = nargs(); i != n; ++i) {
3949                 if (bv.coordCache().getInsets().has(tabular.getCellInset(i).get())) {
3950                         int const d = dist(bv, i, x, y);
3951                         if (d < dist_min) {
3952                                 dist_min = d;
3953                                 idx_min = i;
3954                         }
3955                 }
3956         }
3957         return idx_min;
3958 }
3959
3960
3961 int InsetTabular::getCellXPos(idx_type const cell) const
3962 {
3963         idx_type c = cell;
3964
3965         for (; !tabular.isFirstCellInRow(c); --c)
3966                 ;
3967         int lx = 0;
3968         for (; c < cell; ++c)
3969                 lx += tabular.columnWidth(c);
3970
3971         return lx;
3972 }
3973
3974
3975 void InsetTabular::resetPos(Cursor & cur) const
3976 {
3977         BufferView & bv = cur.bv();
3978         int const maxwidth = bv.workWidth();
3979
3980         if (&cur.inset() != this) {
3981                 scx_ = 0;
3982         } else {
3983                 int const X1 = 0;
3984                 int const X2 = maxwidth;
3985                 int const offset = ADD_TO_TABULAR_WIDTH + 2;
3986                 int const x1 = xo(cur.bv()) + getCellXPos(cur.idx()) + offset;
3987                 int const x2 = x1 + tabular.columnWidth(cur.idx());
3988
3989                 if (x1 < X1)
3990                         scx_ = X1 + 20 - x1;
3991                 else if (x2 > X2)
3992                         scx_ = X2 - 20 - x2;
3993                 else
3994                         scx_ = 0;
3995         }
3996
3997         cur.updateFlags(Update::Force | Update::FitCursor);
3998 }
3999
4000
4001 void InsetTabular::moveNextCell(Cursor & cur)
4002 {
4003         if (isRightToLeft(cur)) {
4004                 if (tabular.isFirstCellInRow(cur.idx())) {
4005                         row_type const row = tabular.cellRow(cur.idx());
4006                         if (row == tabular.rowCount() - 1)
4007                                 return;
4008                         cur.idx() = tabular.getCellBelow(tabular.getLastCellInRow(row));
4009                 } else {
4010                         if (cur.idx() == 0)
4011                                 return;
4012                         --cur.idx();
4013                 }
4014         } else {
4015                 if (tabular.isLastCell(cur.idx()))
4016                         return;
4017                 ++cur.idx();
4018         }
4019         cur.pit() = 0;
4020         cur.pos() = 0;
4021         resetPos(cur);
4022 }
4023
4024
4025 void InsetTabular::movePrevCell(Cursor & cur)
4026 {
4027         if (isRightToLeft(cur)) {
4028                 if (tabular.isLastCellInRow(cur.idx())) {
4029                         row_type const row = tabular.cellRow(cur.idx());
4030                         if (row == 0)
4031                                 return;
4032                         cur.idx() = tabular.getFirstCellInRow(row);
4033                         cur.idx() = tabular.getCellAbove(cur.idx());
4034                 } else {
4035                         if (tabular.isLastCell(cur.idx()))
4036                                 return;
4037                         ++cur.idx();
4038                 }
4039         } else {
4040                 if (cur.idx() == 0) // first cell
4041                         return;
4042                 --cur.idx();
4043         }
4044         cur.pit() = cur.lastpit();
4045         cur.pos() = cur.lastpos();
4046
4047         // FIXME: this accesses the position cache before it is initialized
4048         //resetPos(cur);
4049 }
4050
4051
4052 bool InsetTabular::tabularFeatures(Cursor & cur, string const & what)
4053 {
4054         Tabular::Feature action = Tabular::LAST_ACTION;
4055
4056         int i = 0;
4057         for (; tabularFeature[i].action != Tabular::LAST_ACTION; ++i) {
4058                 string const tmp = tabularFeature[i].feature;
4059
4060                 if (tmp == what.substr(0, tmp.length())) {
4061                         //if (!compare(tabularFeatures[i].feature.c_str(), what.c_str(),
4062                         //tabularFeatures[i].feature.length()))
4063                         action = tabularFeature[i].action;
4064                         break;
4065                 }
4066         }
4067         if (action == Tabular::LAST_ACTION)
4068                 return false;
4069
4070         string const val =
4071                 ltrim(what.substr(tabularFeature[i].feature.length()));
4072         tabularFeatures(cur, action, val);
4073         return true;
4074 }
4075
4076
4077 static void checkLongtableSpecial(Tabular::ltType & ltt,
4078                           string const & special, bool & flag)
4079 {
4080         if (special == "dl_above") {
4081                 ltt.topDL = flag;
4082                 ltt.set = false;
4083         } else if (special == "dl_below") {
4084                 ltt.bottomDL = flag;
4085                 ltt.set = false;
4086         } else if (special == "empty") {
4087                 ltt.empty = flag;
4088                 ltt.set = false;
4089         } else if (flag) {
4090                 ltt.empty = false;
4091                 ltt.set = true;
4092         }
4093 }
4094
4095 bool InsetTabular::oneCellHasRotationState(bool rotated,
4096                 row_type row_start, row_type row_end,
4097                 col_type col_start, col_type col_end) const {
4098
4099         for (row_type i = row_start; i <= row_end; ++i) {
4100                 for (col_type j = col_start; j <= col_end; ++j) {
4101                         if (tabular.getRotateCell(tabular.cellIndex(i, j))
4102                                 == rotated) {
4103                                 return true;
4104                         }
4105                 }
4106         }
4107         return false;
4108 }
4109
4110 void InsetTabular::tabularFeatures(Cursor & cur,
4111         Tabular::Feature feature, string const & value)
4112 {
4113         BufferView & bv = cur.bv();
4114         col_type sel_col_start;
4115         col_type sel_col_end;
4116         row_type sel_row_start;
4117         row_type sel_row_end;
4118         bool setLines = false;
4119         LyXAlignment setAlign = LYX_ALIGN_LEFT;
4120         Tabular::VAlignment setVAlign = Tabular::LYX_VALIGN_TOP;
4121
4122         switch (feature) {
4123
4124         case Tabular::M_ALIGN_LEFT:
4125         case Tabular::ALIGN_LEFT:
4126                 setAlign = LYX_ALIGN_LEFT;
4127                 break;
4128
4129         case Tabular::M_ALIGN_RIGHT:
4130         case Tabular::ALIGN_RIGHT:
4131                 setAlign = LYX_ALIGN_RIGHT;
4132                 break;
4133
4134         case Tabular::M_ALIGN_CENTER:
4135         case Tabular::ALIGN_CENTER:
4136                 setAlign = LYX_ALIGN_CENTER;
4137                 break;
4138
4139         case Tabular::ALIGN_BLOCK:
4140                 setAlign = LYX_ALIGN_BLOCK;
4141                 break;
4142
4143         case Tabular::M_VALIGN_TOP:
4144         case Tabular::VALIGN_TOP:
4145                 setVAlign = Tabular::LYX_VALIGN_TOP;
4146                 break;
4147
4148         case Tabular::M_VALIGN_BOTTOM:
4149         case Tabular::VALIGN_BOTTOM:
4150                 setVAlign = Tabular::LYX_VALIGN_BOTTOM;
4151                 break;
4152
4153         case Tabular::M_VALIGN_MIDDLE:
4154         case Tabular::VALIGN_MIDDLE:
4155                 setVAlign = Tabular::LYX_VALIGN_MIDDLE;
4156                 break;
4157
4158         default:
4159                 break;
4160         }
4161
4162         cur.recordUndoInset(ATOMIC_UNDO);
4163
4164         getSelection(cur, sel_row_start, sel_row_end, sel_col_start, sel_col_end);
4165         row_type const row = tabular.cellRow(cur.idx());
4166         col_type const column = tabular.cellColumn(cur.idx());
4167         bool flag = true;
4168         Tabular::ltType ltt;
4169
4170         switch (feature) {
4171
4172         case Tabular::SET_PWIDTH: {
4173                 Length const len(value);
4174                 tabular.setColumnPWidth(cur, cur.idx(), len);
4175                 if (len.zero()
4176                     && tabular.getAlignment(cur.idx(), true) == LYX_ALIGN_BLOCK)
4177                         tabularFeatures(cur, Tabular::ALIGN_CENTER, string());
4178                 break;
4179         }
4180
4181         case Tabular::SET_MPWIDTH:
4182                 tabular.setMColumnPWidth(cur, cur.idx(), Length(value));
4183                 break;
4184
4185         case Tabular::SET_SPECIAL_COLUMN:
4186         case Tabular::SET_SPECIAL_MULTI:
4187                 tabular.setAlignSpecial(cur.idx(), from_utf8(value), feature);
4188                 break;
4189
4190         case Tabular::APPEND_ROW:
4191                 // append the row into the tabular
4192                 tabular.appendRow(bv.buffer().params(), cur.idx());
4193                 break;
4194
4195         case Tabular::APPEND_COLUMN:
4196                 // append the column into the tabular
4197                 tabular.appendColumn(bv.buffer().params(), cur.idx());
4198                 cur.idx() = tabular.cellIndex(row, column);
4199                 break;
4200
4201         case Tabular::DELETE_ROW:
4202                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4203                         tabular.deleteRow(sel_row_start);
4204                 if (sel_row_start >= tabular.rowCount())
4205                         --sel_row_start;
4206                 cur.idx() = tabular.cellIndex(sel_row_start, column);
4207                 cur.pit() = 0;
4208                 cur.pos() = 0;
4209                 cur.selection() = false;
4210                 break;
4211
4212         case Tabular::DELETE_COLUMN:
4213                 for (col_type i = sel_col_start; i <= sel_col_end; ++i)
4214                         tabular.deleteColumn(sel_col_start);
4215                 if (sel_col_start >= tabular.columnCount())
4216                         --sel_col_start;
4217                 cur.idx() = tabular.cellIndex(row, sel_col_start);
4218                 cur.pit() = 0;
4219                 cur.pos() = 0;
4220                 cur.selection() = false;
4221                 break;
4222
4223         case Tabular::COPY_ROW:
4224                 tabular.copyRow(bv.buffer().params(), row);
4225                 break;
4226
4227         case Tabular::COPY_COLUMN:
4228                 tabular.copyColumn(bv.buffer().params(), column);
4229                 cur.idx() = tabular.cellIndex(row, column);
4230                 break;
4231
4232         case Tabular::M_TOGGLE_LINE_TOP:
4233                 flag = false;
4234         case Tabular::TOGGLE_LINE_TOP: {
4235                 bool lineSet = !tabular.topLine(cur.idx(), flag);
4236                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4237                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
4238                                 tabular.setTopLine(
4239                                         tabular.cellIndex(i, j),
4240                                         lineSet, flag);
4241                 break;
4242         }
4243
4244         case Tabular::M_TOGGLE_LINE_BOTTOM:
4245                 flag = false;
4246         case Tabular::TOGGLE_LINE_BOTTOM: {
4247                 bool lineSet = !tabular.bottomLine(cur.idx(), flag);
4248                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4249                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
4250                                 tabular.setBottomLine(
4251                                         tabular.cellIndex(i, j),
4252                                         lineSet,
4253                                         flag);
4254                 break;
4255         }
4256
4257         case Tabular::M_TOGGLE_LINE_LEFT:
4258                 flag = false;
4259         case Tabular::TOGGLE_LINE_LEFT: {
4260                 bool lineSet = !tabular.leftLine(cur.idx(), flag);
4261                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4262                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
4263                                 tabular.setLeftLine(
4264                                         tabular.cellIndex(i,j),
4265                                         lineSet,
4266                                         flag);
4267                 break;
4268         }
4269
4270         case Tabular::M_TOGGLE_LINE_RIGHT:
4271                 flag = false;
4272         case Tabular::TOGGLE_LINE_RIGHT: {
4273                 bool lineSet = !tabular.rightLine(cur.idx(), flag);
4274                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4275                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
4276                                 tabular.setRightLine(
4277                                         tabular.cellIndex(i,j),
4278                                         lineSet,
4279                                         flag);
4280                 break;
4281         }
4282
4283         case Tabular::M_ALIGN_LEFT:
4284         case Tabular::M_ALIGN_RIGHT:
4285         case Tabular::M_ALIGN_CENTER:
4286                 flag = false;
4287         case Tabular::ALIGN_LEFT:
4288         case Tabular::ALIGN_RIGHT:
4289         case Tabular::ALIGN_CENTER:
4290         case Tabular::ALIGN_BLOCK:
4291                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4292                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
4293                                 tabular.setAlignment(
4294                                         tabular.cellIndex(i, j),
4295                                         setAlign,
4296                                         flag);
4297                 break;
4298
4299         case Tabular::M_VALIGN_TOP:
4300         case Tabular::M_VALIGN_BOTTOM:
4301         case Tabular::M_VALIGN_MIDDLE:
4302                 flag = false;
4303         case Tabular::VALIGN_TOP:
4304         case Tabular::VALIGN_BOTTOM:
4305         case Tabular::VALIGN_MIDDLE:
4306                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4307                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
4308                                 tabular.setVAlignment(
4309                                         tabular.cellIndex(i, j),
4310                                         setVAlign, flag);
4311                 break;
4312
4313         case Tabular::MULTICOLUMN: {
4314                 if (sel_row_start != sel_row_end) {
4315                         // FIXME: Need I say it ? This is horrible.
4316                         // FIXME UNICODE
4317                         Alert::error(_("Error setting multicolumn"),
4318                                      _("You cannot set multicolumn vertically."));
4319                         return;
4320                 }
4321                 if (!cur.selection()) {
4322                         // just multicol for one single cell
4323                         // check whether we are completely in a multicol
4324                         if (tabular.isMultiColumn(cur.idx()))
4325                                 tabular.unsetMultiColumn(cur.idx());
4326                         else
4327                                 tabular.setMultiColumn(&bv.buffer(), cur.idx(), 1);
4328                         break;
4329                 }
4330                 // we have a selection so this means we just add all this
4331                 // cells to form a multicolumn cell
4332                 idx_type const s_start = cur.selBegin().idx();
4333                 idx_type const s_end = cur.selEnd().idx();
4334                 tabular.setMultiColumn(&bv.buffer(), s_start, s_end - s_start + 1);
4335                 cur.idx() = s_start;
4336                 cur.pit() = 0;
4337                 cur.pos() = 0;
4338                 cur.selection() = false;
4339                 break;
4340         }
4341
4342         case Tabular::SET_ALL_LINES:
4343                 setLines = true;
4344         case Tabular::UNSET_ALL_LINES:
4345                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4346                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
4347                                 tabular.setAllLines(
4348                                         tabular.cellIndex(i,j), setLines);
4349                 break;
4350
4351         case Tabular::SET_LONGTABULAR:
4352                 tabular.setLongTabular(true);
4353                 break;
4354
4355         case Tabular::UNSET_LONGTABULAR:
4356                 tabular.setLongTabular(false);
4357                 break;
4358
4359         case Tabular::SET_ROTATE_TABULAR:
4360                 tabular.setRotateTabular(true);
4361                 break;
4362
4363         case Tabular::UNSET_ROTATE_TABULAR:
4364                 tabular.setRotateTabular(false);
4365                 break;
4366
4367         case Tabular::TOGGLE_ROTATE_TABULAR:
4368                 tabular.setRotateTabular(!tabular.getRotateTabular());
4369                 break;
4370
4371         case Tabular::SET_ROTATE_CELL:
4372                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4373                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
4374                                 tabular.setRotateCell(
4375                                         tabular.cellIndex(i, j), true);
4376                 break;
4377
4378         case Tabular::UNSET_ROTATE_CELL:
4379                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4380                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
4381                                 tabular.setRotateCell(
4382                                         tabular.cellIndex(i, j), false);
4383                 break;
4384
4385         case Tabular::TOGGLE_ROTATE_CELL:
4386                 {
4387                 bool oneNotRotated = oneCellHasRotationState(false,
4388                         sel_row_start, sel_row_end, sel_col_start, sel_col_end);
4389
4390                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4391                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
4392                                 tabular.setRotateCell(tabular.cellIndex(i, j),
4393                                                                           oneNotRotated);
4394                 }
4395                 break;
4396
4397         case Tabular::SET_USEBOX: {
4398                 Tabular::BoxType val = Tabular::BoxType(convert<int>(value));
4399                 if (val == tabular.getUsebox(cur.idx()))
4400                         val = Tabular::BOX_NONE;
4401                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4402                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
4403                                 tabular.setUsebox(tabular.cellIndex(i, j), val);
4404                 break;
4405         }
4406
4407         case Tabular::UNSET_LTFIRSTHEAD:
4408                 flag = false;
4409         case Tabular::SET_LTFIRSTHEAD:
4410                 tabular.getRowOfLTFirstHead(row, ltt);
4411                 checkLongtableSpecial(ltt, value, flag);
4412                 tabular.setLTHead(row, flag, ltt, true);
4413                 break;
4414
4415         case Tabular::UNSET_LTHEAD:
4416                 flag = false;
4417         case Tabular::SET_LTHEAD:
4418                 tabular.getRowOfLTHead(row, ltt);
4419                 checkLongtableSpecial(ltt, value, flag);
4420                 tabular.setLTHead(row, flag, ltt, false);
4421                 break;
4422
4423         case Tabular::UNSET_LTFOOT:
4424                 flag = false;
4425         case Tabular::SET_LTFOOT:
4426                 tabular.getRowOfLTFoot(row, ltt);
4427                 checkLongtableSpecial(ltt, value, flag);
4428                 tabular.setLTFoot(row, flag, ltt, false);
4429                 break;
4430
4431         case Tabular::UNSET_LTLASTFOOT:
4432                 flag = false;
4433         case Tabular::SET_LTLASTFOOT:
4434                 tabular.getRowOfLTLastFoot(row, ltt);
4435                 checkLongtableSpecial(ltt, value, flag);
4436                 tabular.setLTFoot(row, flag, ltt, true);
4437                 break;
4438
4439         case Tabular::SET_LTNEWPAGE:
4440                 tabular.setLTNewPage(row, !tabular.getLTNewPage(row));
4441                 break;
4442
4443         case Tabular::SET_BOOKTABS:
4444                 tabular.setBookTabs(true);
4445                 break;
4446
4447         case Tabular::UNSET_BOOKTABS:
4448                 tabular.setBookTabs(false);
4449                 break;
4450
4451         case Tabular::SET_TOP_SPACE: {
4452                 Length len;
4453                 if (value == "default")
4454                         for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4455                                 tabular.row_info[i].top_space_default = true;
4456                 else if (isValidLength(value, &len))
4457                         for (row_type i = sel_row_start; i <= sel_row_end; ++i) {
4458                                 tabular.row_info[i].top_space_default = false;
4459                                 tabular.row_info[i].top_space = len;
4460                         }
4461                 else
4462                         for (row_type i = sel_row_start; i <= sel_row_end; ++i) {
4463                                 tabular.row_info[i].top_space_default = false;
4464                                 tabular.row_info[i].top_space = len;
4465                         }
4466                 break;
4467         }
4468
4469         case Tabular::SET_BOTTOM_SPACE: {
4470                 Length len;
4471                 if (value == "default")
4472                         for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4473                                 tabular.row_info[i].bottom_space_default = true;
4474                 else if (isValidLength(value, &len))
4475                         for (row_type i = sel_row_start; i <= sel_row_end; ++i) {
4476                                 tabular.row_info[i].bottom_space_default = false;
4477                                 tabular.row_info[i].bottom_space = len;
4478                         }
4479                 else
4480                         for (row_type i = sel_row_start; i <= sel_row_end; ++i) {
4481                                 tabular.row_info[i].bottom_space_default = false;
4482                                 tabular.row_info[i].bottom_space = len;
4483                         }
4484                 break;
4485         }
4486
4487         case Tabular::SET_INTERLINE_SPACE: {
4488                 Length len;
4489                 if (value == "default")
4490                         for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4491                                 tabular.row_info[i].interline_space_default = true;
4492                 else if (isValidLength(value, &len))
4493                         for (row_type i = sel_row_start; i <= sel_row_end; ++i) {
4494                                 tabular.row_info[i].interline_space_default = false;
4495                                 tabular.row_info[i].interline_space = len;
4496                         }
4497                 else
4498                         for (row_type i = sel_row_start; i <= sel_row_end; ++i) {
4499                                 tabular.row_info[i].interline_space_default = false;
4500                                 tabular.row_info[i].interline_space = len;
4501                         }
4502                 break;
4503         }
4504
4505         // dummy stuff just to avoid warnings
4506         case Tabular::LAST_ACTION:
4507                 break;
4508         }
4509 }
4510
4511
4512 bool InsetTabular::showInsetDialog(BufferView * bv) const
4513 {
4514         InsetTabularMailer(*this).showDialog(bv);
4515         return true;
4516 }
4517
4518
4519 void InsetTabular::openLayoutDialog(BufferView * bv) const
4520 {
4521         InsetTabularMailer(*this).showDialog(bv);
4522 }
4523
4524
4525 bool InsetTabular::copySelection(Cursor & cur)
4526 {
4527         if (!cur.selection())
4528                 return false;
4529
4530         row_type rs, re;
4531         col_type cs, ce;
4532         getSelection(cur, rs, re, cs, ce);
4533
4534         paste_tabular.reset(new Tabular(tabular));
4535
4536         for (row_type i = 0; i < rs; ++i)
4537                 paste_tabular->deleteRow(0);
4538
4539         row_type const rows = re - rs + 1;
4540         while (paste_tabular->rowCount() > rows)
4541                 paste_tabular->deleteRow(rows);
4542
4543         paste_tabular->setTopLine(0, true, true);
4544         paste_tabular->setBottomLine(paste_tabular->getFirstCellInRow(rows - 1),
4545                                      true, true);
4546
4547         for (col_type i = 0; i < cs; ++i)
4548                 paste_tabular->deleteColumn(0);
4549
4550         col_type const columns = ce - cs + 1;
4551         while (paste_tabular->columnCount() > columns)
4552                 paste_tabular->deleteColumn(columns);
4553
4554         paste_tabular->setLeftLine(0, true, true);
4555         paste_tabular->setRightLine(paste_tabular->getLastCellInRow(0),
4556                                     true, true);
4557
4558         odocstringstream os;
4559         OutputParams const runparams(0);
4560         paste_tabular->plaintext(cur.buffer(), os, runparams, 0, true, '\t');
4561         // Needed for the "Edit->Paste recent" menu and the system clipboard.
4562         cap::copySelection(cur, os.str());
4563
4564         // mark tabular stack dirty
4565         // FIXME: this is a workaround for bug 1919. Should be removed for 1.5,
4566         // when we (hopefully) have a one-for-all paste mechanism.
4567         // This must be called after cap::copySelection.
4568         dirtyTabularStack(true);
4569
4570         return true;
4571 }
4572
4573
4574 bool InsetTabular::pasteClipboard(Cursor & cur)
4575 {
4576         if (!paste_tabular)
4577                 return false;
4578         col_type const actcol = tabular.cellColumn(cur.idx());
4579         row_type const actrow = tabular.cellRow(cur.idx());
4580         for (row_type r1 = 0, r2 = actrow;
4581              r1 < paste_tabular->rowCount() && r2 < tabular.rowCount();
4582              ++r1, ++r2) {
4583                 for (col_type c1 = 0, c2 = actcol;
4584                     c1 < paste_tabular->columnCount() && c2 < tabular.columnCount();
4585                     ++c1, ++c2) {
4586                         if (paste_tabular->isPartOfMultiColumn(r1, c1) &&
4587                             tabular.isPartOfMultiColumn(r2, c2))
4588                                 continue;
4589                         if (paste_tabular->isPartOfMultiColumn(r1, c1)) {
4590                                 --c2;
4591                                 continue;
4592                         }
4593                         if (tabular.isPartOfMultiColumn(r2, c2)) {
4594                                 --c1;
4595                                 continue;
4596                         }
4597                         shared_ptr<InsetText> inset(
4598                                 new InsetText(*paste_tabular->getCellInset(r1, c1)));
4599                         tabular.setCellInset(r2, c2, inset);
4600                         // FIXME: change tracking (MG)
4601                         inset->setChange(Change(cur.buffer().params().trackChanges ?
4602                                                 Change::INSERTED : Change::UNCHANGED));
4603                         cur.pos() = 0;
4604                 }
4605         }
4606         return true;
4607 }
4608
4609
4610 void InsetTabular::cutSelection(Cursor & cur)
4611 {
4612         if (!cur.selection())
4613                 return;
4614
4615         row_type rs, re;
4616         col_type cs, ce;
4617         getSelection(cur, rs, re, cs, ce);
4618         for (row_type i = rs; i <= re; ++i) {
4619                 for (col_type j = cs; j <= ce; ++j) {
4620                         shared_ptr<InsetText> t
4621                                 = cell(tabular.cellIndex(i, j));
4622                         if (cur.buffer().params().trackChanges)
4623                                 // FIXME: Change tracking (MG)
4624                                 t->setChange(Change(Change::DELETED));
4625                         else
4626                                 t->clear();
4627                 }
4628         }
4629
4630         // cursor position might be invalid now
4631         if (cur.pit() > cur.lastpit())
4632                 cur.pit() = cur.lastpit();
4633         if (cur.pos() > cur.lastpos())
4634                 cur.pos() = cur.lastpos();
4635         cur.clearSelection();
4636 }
4637
4638
4639 bool InsetTabular::isRightToLeft(Cursor & cur) const
4640 {
4641         BOOST_ASSERT(cur.depth() > 1);
4642         Paragraph const & parentpar = cur[cur.depth() - 2].paragraph();
4643         pos_type const parentpos = cur[cur.depth() - 2].pos();
4644         return parentpar.getFontSettings(cur.bv().buffer().params(),
4645                                          parentpos).language()->rightToLeft();
4646 }
4647
4648
4649 void InsetTabular::getSelection(Cursor & cur,
4650         row_type & rs, row_type & re, col_type & cs, col_type & ce) const
4651 {
4652         CursorSlice const & beg = cur.selBegin();
4653         CursorSlice const & end = cur.selEnd();
4654         cs = tabular.cellColumn(beg.idx());
4655         ce = tabular.cellColumn(end.idx());
4656         if (cs > ce) {
4657                 ce = cs;
4658                 cs = tabular.cellColumn(end.idx());
4659         } else {
4660                 ce = tabular.cellRightColumn(end.idx());
4661         }
4662
4663         rs = tabular.cellRow(beg.idx());
4664         re = tabular.cellRow(end.idx());
4665         if (rs > re)
4666                 swap(rs, re);
4667 }
4668
4669
4670 Text * InsetTabular::getText(int idx) const
4671 {
4672         return size_t(idx) < nargs() ? cell(idx)->getText(0) : 0;
4673 }
4674
4675
4676 void InsetTabular::setChange(Change const & change)
4677 {
4678         for (idx_type idx = 0; idx < nargs(); ++idx)
4679                 cell(idx)->setChange(change);
4680 }
4681
4682
4683 void InsetTabular::acceptChanges(BufferParams const & bparams)
4684 {
4685         for (idx_type idx = 0; idx < nargs(); ++idx)
4686                 cell(idx)->acceptChanges(bparams);
4687 }
4688
4689
4690 void InsetTabular::rejectChanges(BufferParams const & bparams)
4691 {
4692         for (idx_type idx = 0; idx < nargs(); ++idx)
4693                 cell(idx)->rejectChanges(bparams);
4694 }
4695
4696
4697 bool InsetTabular::forceDefaultParagraphs(idx_type cell) const
4698 {
4699         return tabular.getPWidth(cell).zero();
4700 }
4701
4702
4703 bool InsetTabular::insertPlaintextString(BufferView & bv, docstring const & buf,
4704                                      bool usePaste)
4705 {
4706         if (buf.length() <= 0)
4707                 return true;
4708
4709         Buffer const & buffer = bv.buffer();
4710
4711         col_type cols = 1;
4712         row_type rows = 1;
4713         col_type maxCols = 1;
4714         docstring::size_type const len = buf.length();
4715         docstring::size_type p = 0;
4716
4717         while (p < len &&
4718                (p = buf.find_first_of(from_ascii("\t\n"), p)) != docstring::npos) {
4719                 switch (buf[p]) {
4720                 case '\t':
4721                         ++cols;
4722                         break;
4723                 case '\n':
4724                         if (p + 1 < len)
4725                                 ++rows;
4726                         maxCols = max(cols, maxCols);
4727                         cols = 1;
4728                         break;
4729                 }
4730                 ++p;
4731         }
4732         maxCols = max(cols, maxCols);
4733         Tabular * loctab;
4734         idx_type cell = 0;
4735         col_type ocol = 0;
4736         row_type row = 0;
4737         if (usePaste) {
4738                 paste_tabular.reset(
4739                         new Tabular(buffer.params(), rows, maxCols));
4740                 loctab = paste_tabular.get();
4741                 cols = 0;
4742                 dirtyTabularStack(true);
4743         } else {
4744                 loctab = &tabular;
4745                 cell = bv.cursor().idx();
4746                 ocol = tabular.cellColumn(cell);
4747                 row = tabular.cellRow(cell);
4748         }
4749
4750         docstring::size_type op = 0;
4751         idx_type const cells = loctab->cellCount();
4752         p = 0;
4753         cols = ocol;
4754         rows = loctab->rowCount();
4755         col_type const columns = loctab->columnCount();
4756
4757         while (cell < cells && p < len && row < rows &&
4758                (p = buf.find_first_of(from_ascii("\t\n"), p)) != docstring::npos)
4759         {
4760                 if (p >= len)
4761                         break;
4762                 switch (buf[p]) {
4763                 case '\t':
4764                         // we can only set this if we are not too far right
4765                         if (cols < columns) {
4766                                 shared_ptr<InsetText> inset = loctab->getCellInset(cell);
4767                                 Font const font = bv.textMetrics(&inset->text_).
4768                                         getDisplayFont(0, 0);
4769                                 inset->setText(buf.substr(op, p - op), font,
4770                                                buffer.params().trackChanges);
4771                                 ++cols;
4772                                 ++cell;
4773                         }
4774                         break;
4775                 case '\n':
4776                         // we can only set this if we are not too far right
4777                         if (cols < columns) {
4778                                 shared_ptr<InsetText> inset = tabular.getCellInset(cell);
4779                                 Font const font = bv.textMetrics(&inset->text_).
4780                                         getDisplayFont(0, 0);
4781                                 inset->setText(buf.substr(op, p - op), font,
4782                                                buffer.params().trackChanges);
4783                         }
4784                         cols = ocol;
4785                         ++row;
4786                         if (row < rows)
4787                                 cell = loctab->cellIndex(row, cols);
4788                         break;
4789                 }
4790                 ++p;
4791                 op = p;
4792         }
4793         // check for the last cell if there is no trailing '\n'
4794         if (cell < cells && op < len) {
4795                 shared_ptr<InsetText> inset = loctab->getCellInset(cell);
4796                 Font const font = bv.textMetrics(&inset->text_).getDisplayFont(0, 0);
4797                 inset->setText(buf.substr(op, len - op), font,
4798                         buffer.params().trackChanges);
4799         }
4800         return true;
4801 }
4802
4803
4804 void InsetTabular::addPreview(PreviewLoader & loader) const
4805 {
4806         row_type const rows = tabular.rowCount();
4807         col_type const columns = tabular.columnCount();
4808         for (row_type i = 0; i < rows; ++i) {
4809                 for (col_type j = 0; j < columns; ++j)
4810                         tabular.getCellInset(i, j)->addPreview(loader);
4811         }
4812 }
4813
4814
4815 bool InsetTabular::tablemode(Cursor & cur) const
4816 {
4817         return cur.selection() && cur.selBegin().idx() != cur.selEnd().idx();
4818 }
4819
4820
4821
4822
4823 string const InsetTabularMailer::name_("tabular");
4824
4825 InsetTabularMailer::InsetTabularMailer(InsetTabular const & inset)
4826         : inset_(const_cast<InsetTabular &>(inset))
4827 {}
4828
4829
4830 string const InsetTabularMailer::inset2string(Buffer const &) const
4831 {
4832         return params2string(inset_);
4833 }
4834
4835
4836 void InsetTabularMailer::string2params(string const & in, InsetTabular & inset)
4837 {
4838         istringstream data(in);
4839         Lexer lex(0,0);
4840         lex.setStream(data);
4841
4842         if (in.empty())
4843                 return;
4844
4845         string token;
4846         lex >> token;
4847         if (!lex || token != name_)
4848                 return print_mailer_error("InsetTabularMailer", in, 1,
4849                                           name_);
4850
4851         // This is part of the inset proper that is usually swallowed
4852         // by Buffer::readInset
4853         lex >> token;
4854         if (!lex || token != "Tabular")
4855                 return print_mailer_error("InsetTabularMailer", in, 2,
4856                                           "Tabular");
4857
4858         Buffer const & buffer = inset.buffer();
4859         inset.read(buffer, lex);
4860 }
4861
4862
4863 string const InsetTabularMailer::params2string(InsetTabular const & inset)
4864 {
4865         ostringstream data;
4866         data << name_ << ' ';
4867         inset.write(inset.buffer(), data);
4868         data << "\\end_inset\n";
4869         return data.str();
4870 }
4871
4872
4873 } // namespace lyx