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