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