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