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