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