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