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