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