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