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