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