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