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