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