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