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