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