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