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