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