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