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