]> git.lyx.org Git - lyx.git/blob - src/insets/InsetTabular.cpp
* InsetTabular.cpp cosmetics
[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                 // if we don't have a multicell selection...
3405                 if (!cur.selIsMultiCell() ||
3406                   // ...or we're not doing some LFUN_*_SELECT thing, anyway...
3407                     (cmd.action != LFUN_CHAR_FORWARD_SELECT &&
3408                      cmd.action != LFUN_CHAR_BACKWARD_SELECT &&
3409                      cmd.action != LFUN_CHAR_RIGHT_SELECT &&
3410                      cmd.action != LFUN_CHAR_LEFT_SELECT)) {
3411                         // ...try to dispatch to the cell's inset.
3412                         cell(cur.idx())->dispatch(cur, cmd);
3413                         if (cur.result().dispatched()) 
3414                                 break;
3415                 }
3416                 // move to next/prev cell, as appropriate
3417                 // note that we will always do this if we're selecting and we have
3418                 // a multicell selection
3419                 LYXERR(Debug::RTL, "entering " << (next_cell ? "next" : "previous")
3420                         << " cell from: " << int(entry_from));
3421                 if (next_cell)
3422                         moveNextCell(cur, entry_from);
3423                 else
3424                         movePrevCell(cur, entry_from);
3425                 // if we're exiting the table, call the appropriate FINISHED lfun
3426                 if (sl == cur.top())
3427                         cmd = FuncRequest(finish_lfun);
3428                 else
3429                         cur.dispatched();
3430                 break;
3431
3432         }
3433
3434         case LFUN_DOWN_SELECT:
3435         case LFUN_DOWN:
3436                 if (!(cur.selection() && cur.selIsMultiCell()))
3437                         cell(cur.idx())->dispatch(cur, cmd);
3438                 
3439                 cur.dispatched(); // override the cell's decision
3440                 if (sl == cur.top()) {
3441                         // if our Text didn't do anything to the cursor
3442                         // then we try to put the cursor into the cell below
3443                         // setting also the right targetX.
3444                         cur.selHandle(cmd.action == LFUN_DOWN_SELECT);
3445                         if (tabular.cellRow(cur.idx()) != tabular.row_info.size() - 1) {
3446                                 cur.idx() = tabular.cellBelow(cur.idx());
3447                                 cur.pit() = 0;
3448                                 TextMetrics const & tm =
3449                                         cur.bv().textMetrics(cell(cur.idx())->getText(0));
3450                                 cur.pos() = tm.x2pos(cur.pit(), 0, cur.targetX());
3451                         }
3452                 }
3453                 if (sl == cur.top()) {
3454                         // we trick it to go to forward after leaving the
3455                         // tabular.
3456                         cmd = FuncRequest(LFUN_FINISHED_FORWARD);
3457                         cur.undispatched();
3458                 }
3459                 if (cur.selIsMultiCell()) {
3460                         cur.pit() = cur.lastpit();
3461                         cur.pos() = cur.lastpos();
3462                         return;
3463                 }
3464                 break;
3465
3466         case LFUN_UP_SELECT:
3467         case LFUN_UP:
3468                 if (!(cur.selection() && cur.selIsMultiCell()))
3469                         cell(cur.idx())->dispatch(cur, cmd);
3470                 cur.dispatched(); // override the cell's decision
3471                 if (sl == cur.top()) {
3472                         // if our Text didn't do anything to the cursor
3473                         // then we try to put the cursor into the cell above
3474                         // setting also the right targetX.
3475                         cur.selHandle(cmd.action == LFUN_UP_SELECT);
3476                         if (tabular.cellRow(cur.idx()) != 0) {
3477                                 cur.idx() = tabular.cellAbove(cur.idx());
3478                                 cur.pit() = cur.lastpit();
3479                                 Text const * text = cell(cur.idx())->getText(0);
3480                                 TextMetrics const & tm = cur.bv().textMetrics(text);
3481                                 ParagraphMetrics const & pm =
3482                                         tm.parMetrics(cur.lastpit());
3483                                 cur.pos() = tm.x2pos(cur.pit(), pm.rows().size()-1, cur.targetX());
3484                         }
3485                 }
3486                 if (sl == cur.top()) {
3487                         cmd = FuncRequest(LFUN_UP);
3488                         cur.undispatched();
3489                 }
3490                 if (cur.selIsMultiCell()) {
3491                         cur.pit() = 0;
3492                         cur.pos() = cur.lastpos();
3493                         return;
3494                 }
3495                 break;
3496
3497 //      case LFUN_SCREEN_DOWN: {
3498 //              //if (hasSelection())
3499 //              //      cur.selection() = false;
3500 //              col_type const col = tabular.cellColumn(cur.idx());
3501 //              int const t =   cur.bv().top_y() + cur.bv().height();
3502 //              if (t < yo() + tabular.getHeightOfTabular()) {
3503 //                      cur.bv().scrollDocView(t);
3504 //                      cur.idx() = tabular.cellBelow(first_visible_cell) + col;
3505 //              } else {
3506 //                      cur.idx() = tabular.getFirstCellInRow(tabular.rows() - 1) + col;
3507 //              }
3508 //              cur.par() = 0;
3509 //              cur.pos() = 0;
3510 //              break;
3511 //      }
3512 //
3513 //      case LFUN_SCREEN_UP: {
3514 //              //if (hasSelection())
3515 //              //      cur.selection() = false;
3516 //              col_type const col = tabular.cellColumn(cur.idx());
3517 //              int const t =   cur.bv().top_y() + cur.bv().height();
3518 //              if (yo() < 0) {
3519 //                      cur.bv().scrollDocView(t);
3520 //                      if (yo() > 0)
3521 //                              cur.idx() = col;
3522 //                      else
3523 //                              cur.idx() = tabular.cellBelow(first_visible_cell) + col;
3524 //              } else {
3525 //                      cur.idx() = col;
3526 //              }
3527 //              cur.par() = cur.lastpar();
3528 //              cur.pos() = cur.lastpos();
3529 //              break;
3530 //      }
3531
3532         case LFUN_LAYOUT_TABULAR:
3533                 cur.bv().showDialog("tabular", params2string(*this), this);
3534                 break;
3535
3536         case LFUN_INSET_DIALOG_UPDATE:
3537                 cur.bv().updateDialog("tabular", params2string(*this));
3538                 break;
3539
3540         case LFUN_TABULAR_FEATURE:
3541                 if (!tabularFeatures(cur, to_utf8(cmd.argument())))
3542                         cur.undispatched();
3543                 break;
3544
3545         // insert file functions
3546         case LFUN_FILE_INSERT_PLAINTEXT_PARA:
3547         case LFUN_FILE_INSERT_PLAINTEXT: {
3548                 // FIXME UNICODE
3549                 docstring const tmpstr = cur.bv().contentsOfPlaintextFile(
3550                         FileName(to_utf8(cmd.argument())));
3551                 if (tmpstr.empty())
3552                         break;
3553                 cur.recordUndoInset(INSERT_UNDO);
3554                 if (insertPlaintextString(cur.bv(), tmpstr, false)) {
3555                         // content has been replaced,
3556                         // so cursor might be invalid
3557                         cur.pos() = cur.lastpos();
3558                         cur.pit() = cur.lastpit();
3559                         bvcur.setCursor(cur);
3560                 } else
3561                         cur.undispatched();
3562                 break;
3563         }
3564
3565         case LFUN_CUT:
3566                 if (cur.selIsMultiCell()) {
3567                         if (copySelection(cur)) {
3568                                 cur.recordUndoInset(DELETE_UNDO);
3569                                 cutSelection(cur);
3570                         }
3571                 }
3572                 else
3573                         cell(cur.idx())->dispatch(cur, cmd);
3574                 break;
3575
3576         case LFUN_SELF_INSERT:
3577                 if (cur.selIsMultiCell()) {
3578                         cur.recordUndoInset(DELETE_UNDO);
3579                         cutSelection(cur);
3580                 }
3581                 cell(cur.idx())->dispatch(cur, cmd);
3582                 break;
3583
3584         case LFUN_CHAR_DELETE_BACKWARD:
3585         case LFUN_CHAR_DELETE_FORWARD:
3586                 if (cur.selIsMultiCell()) {
3587                         cur.recordUndoInset(DELETE_UNDO);
3588                         cutSelection(cur);
3589                 }
3590                 else
3591                         cell(cur.idx())->dispatch(cur, cmd);
3592                 break;
3593
3594         case LFUN_COPY:
3595                 if (!cur.selection())
3596                         break;
3597                 if (cur.selIsMultiCell()) {
3598                         cur.finishUndo();
3599                         copySelection(cur);
3600                 } else
3601                         cell(cur.idx())->dispatch(cur, cmd);
3602                 break;
3603
3604         case LFUN_CLIPBOARD_PASTE:
3605         case LFUN_PRIMARY_SELECTION_PASTE: {
3606                 docstring const clip = (cmd.action == LFUN_CLIPBOARD_PASTE) ?
3607                         theClipboard().getAsText() :
3608                         theSelection().get();
3609                 if (clip.empty())
3610                         break;
3611                 // pass to InsertPlaintextString, but
3612                 // only if we have multi-cell content
3613                 if (clip.find_first_of(from_ascii("\t\n")) != docstring::npos) {
3614                         cur.recordUndoInset(INSERT_UNDO);
3615                         if (insertPlaintextString(cur.bv(), clip, false)) {
3616                                 // content has been replaced,
3617                                 // so cursor might be invalid
3618                                 cur.pos() = cur.lastpos();
3619                                 cur.pit() = cur.lastpit();
3620                                 bvcur.setCursor(cur);
3621                                 break;
3622                         }
3623                 }
3624                 // Let the cell handle normal text
3625                 cell(cur.idx())->dispatch(cur, cmd);
3626                 break;
3627         }
3628
3629         case LFUN_PASTE:
3630                 if (!tabularStackDirty()) {
3631                         cell(cur.idx())->dispatch(cur, cmd);
3632                         break;
3633                 }
3634                 if (theClipboard().isInternal() ||
3635                     (!theClipboard().hasInternal() && theClipboard().hasLyXContents())) {
3636                         cur.recordUndoInset(INSERT_UNDO);
3637                         pasteClipboard(cur);
3638                 }
3639                 break;
3640
3641         case LFUN_FONT_EMPH:
3642         case LFUN_FONT_BOLD:
3643         case LFUN_FONT_BOLDSYMBOL:
3644         case LFUN_FONT_ROMAN:
3645         case LFUN_FONT_NOUN:
3646         case LFUN_FONT_ITAL:
3647         case LFUN_FONT_FRAK:
3648         case LFUN_FONT_TYPEWRITER:
3649         case LFUN_FONT_SANS:
3650         case LFUN_TEXTSTYLE_APPLY:
3651         case LFUN_TEXTSTYLE_UPDATE:
3652         case LFUN_FONT_SIZE:
3653         case LFUN_FONT_UNDERLINE:
3654         case LFUN_LANGUAGE:
3655         case LFUN_WORD_CAPITALIZE:
3656         case LFUN_WORD_UPCASE:
3657         case LFUN_WORD_LOWCASE:
3658         case LFUN_CHARS_TRANSPOSE:
3659                 if (cur.selIsMultiCell()) {
3660                         row_type rs, re;
3661                         col_type cs, ce;
3662                         getSelection(cur, rs, re, cs, ce);
3663                         Cursor tmpcur = cur;
3664                         for (row_type i = rs; i <= re; ++i) {
3665                                 for (col_type j = cs; j <= ce; ++j) {
3666                                         // cursor follows cell:
3667                                         tmpcur.idx() = tabular.cellIndex(i, j);
3668                                         // select this cell only:
3669                                         tmpcur.pit() = 0;
3670                                         tmpcur.pos() = 0;
3671                                         tmpcur.resetAnchor();
3672                                         tmpcur.pit() = tmpcur.lastpit();
3673                                         tmpcur.pos() = tmpcur.top().lastpos();
3674                                         tmpcur.setCursor(tmpcur);
3675                                         tmpcur.setSelection();
3676                                         cell(tmpcur.idx())->dispatch(tmpcur, cmd);
3677                                 }
3678                         }
3679                         break;
3680                 } else {
3681                         cell(cur.idx())->dispatch(cur, cmd);
3682                         break;
3683                 }
3684         default:
3685                 // we try to handle this event in the insets dispatch function.
3686                 cell(cur.idx())->dispatch(cur, cmd);
3687                 break;
3688         }
3689 }
3690
3691
3692 // function sets an object as defined in func_status.h:
3693 // states OK, Unknown, Disabled, On, Off.
3694 bool InsetTabular::getStatus(Cursor & cur, FuncRequest const & cmd,
3695         FuncStatus & status) const
3696 {
3697         switch (cmd.action) {
3698         case LFUN_TABULAR_FEATURE: {
3699                 int action = Tabular::LAST_ACTION;
3700                 int i = 0;
3701                 for (; tabularFeature[i].action != Tabular::LAST_ACTION; ++i) {
3702                         string const tmp = tabularFeature[i].feature;
3703                         if (tmp == to_utf8(cmd.argument()).substr(0, tmp.length())) {
3704                                 action = tabularFeature[i].action;
3705                                 break;
3706                         }
3707                 }
3708                 if (action == Tabular::LAST_ACTION) {
3709                         status.clear();
3710                         status.unknown(true);
3711                         return true;
3712                 }
3713
3714                 string const argument
3715                         = ltrim(to_utf8(cmd.argument()).substr(tabularFeature[i].feature.length()));
3716
3717                 row_type sel_row_start = 0;
3718                 row_type sel_row_end = 0;
3719                 col_type sel_col_start = 0;
3720                 col_type sel_col_end = 0;
3721                 Tabular::ltType dummyltt;
3722                 bool flag = true;
3723
3724                 getSelection(cur, sel_row_start, sel_row_end, sel_col_start, sel_col_end);
3725
3726                 switch (action) {
3727                 case Tabular::SET_PWIDTH:
3728                 case Tabular::SET_MPWIDTH:
3729                 case Tabular::SET_SPECIAL_COLUMN:
3730                 case Tabular::SET_SPECIAL_MULTI:
3731                 case Tabular::APPEND_ROW:
3732                 case Tabular::APPEND_COLUMN:
3733                 case Tabular::DELETE_ROW:
3734                 case Tabular::DELETE_COLUMN:
3735                 case Tabular::COPY_ROW:
3736                 case Tabular::COPY_COLUMN:
3737                 case Tabular::SET_TOP_SPACE:
3738                 case Tabular::SET_BOTTOM_SPACE:
3739                 case Tabular::SET_INTERLINE_SPACE:
3740                         status.clear();
3741                         return true;
3742
3743                 case Tabular::MULTICOLUMN:
3744                         status.setEnabled(sel_row_start == sel_row_end);
3745                         status.setOnOff(tabular.isMultiColumn(cur.idx()));
3746                         break;
3747
3748                 case Tabular::SET_ALL_LINES:
3749                 case Tabular::UNSET_ALL_LINES:
3750                 case Tabular::SET_BORDER_LINES:
3751                         status.setEnabled(!tabular.ltCaption(tabular.cellRow(cur.idx())));
3752                         break;
3753
3754                 case Tabular::TOGGLE_LINE_TOP:
3755                         status.setEnabled(!tabular.ltCaption(tabular.cellRow(cur.idx())));
3756                         status.setOnOff(tabular.topLine(cur.idx()));
3757                         break;
3758
3759                 case Tabular::TOGGLE_LINE_BOTTOM:
3760                         status.setEnabled(!tabular.ltCaption(tabular.cellRow(cur.idx())));
3761                         status.setOnOff(tabular.bottomLine(cur.idx()));
3762                         break;
3763
3764                 case Tabular::TOGGLE_LINE_LEFT:
3765                         status.setEnabled(!tabular.ltCaption(tabular.cellRow(cur.idx())));
3766                         status.setOnOff(tabular.leftLine(cur.idx()));
3767                         break;
3768
3769                 case Tabular::TOGGLE_LINE_RIGHT:
3770                         status.setEnabled(!tabular.ltCaption(tabular.cellRow(cur.idx())));
3771                         status.setOnOff(tabular.rightLine(cur.idx()));
3772                         break;
3773
3774                 case Tabular::M_ALIGN_LEFT:
3775                         flag = false;
3776                 case Tabular::ALIGN_LEFT:
3777                         status.setOnOff(tabular.getAlignment(cur.idx(), flag) == LYX_ALIGN_LEFT);
3778                         break;
3779
3780                 case Tabular::M_ALIGN_RIGHT:
3781                         flag = false;
3782                 case Tabular::ALIGN_RIGHT:
3783                         status.setOnOff(tabular.getAlignment(cur.idx(), flag) == LYX_ALIGN_RIGHT);
3784                         break;
3785
3786                 case Tabular::M_ALIGN_CENTER:
3787                         flag = false;
3788                 case Tabular::ALIGN_CENTER:
3789                         status.setOnOff(tabular.getAlignment(cur.idx(), flag) == LYX_ALIGN_CENTER);
3790                         break;
3791
3792                 case Tabular::ALIGN_BLOCK:
3793                         status.setEnabled(!tabular.getPWidth(cur.idx()).zero());
3794                         status.setOnOff(tabular.getAlignment(cur.idx(), flag) == LYX_ALIGN_BLOCK);
3795                         break;
3796
3797                 case Tabular::M_VALIGN_TOP:
3798                         flag = false;
3799                 case Tabular::VALIGN_TOP:
3800                         status.setOnOff(
3801                                 tabular.getVAlignment(cur.idx(), flag) == Tabular::LYX_VALIGN_TOP);
3802                         break;
3803
3804                 case Tabular::M_VALIGN_BOTTOM:
3805                         flag = false;
3806                 case Tabular::VALIGN_BOTTOM:
3807                         status.setOnOff(
3808                                 tabular.getVAlignment(cur.idx(), flag) == Tabular::LYX_VALIGN_BOTTOM);
3809                         break;
3810
3811                 case Tabular::M_VALIGN_MIDDLE:
3812                         flag = false;
3813                 case Tabular::VALIGN_MIDDLE:
3814                         status.setOnOff(
3815                                 tabular.getVAlignment(cur.idx(), flag) == Tabular::LYX_VALIGN_MIDDLE);
3816                         break;
3817
3818                 case Tabular::SET_LONGTABULAR:
3819                         status.setOnOff(tabular.is_long_tabular);
3820                         break;
3821
3822                 case Tabular::UNSET_LONGTABULAR:
3823                         status.setOnOff(!tabular.is_long_tabular);
3824                         break;
3825
3826                 case Tabular::TOGGLE_ROTATE_TABULAR:
3827                 case Tabular::SET_ROTATE_TABULAR:
3828                         status.setOnOff(tabular.rotate);
3829                         break;
3830
3831                 case Tabular::TABULAR_VALIGN_TOP:
3832                         status.setOnOff(tabular.tabular_valignment 
3833                                 == Tabular::LYX_VALIGN_TOP);
3834                         break;
3835                 case Tabular::TABULAR_VALIGN_MIDDLE:
3836                         status.setOnOff(tabular.tabular_valignment 
3837                                 == Tabular::LYX_VALIGN_MIDDLE);
3838                         break;
3839                 case Tabular::TABULAR_VALIGN_BOTTOM:
3840                         status.setOnOff(tabular.tabular_valignment 
3841                                 == Tabular::LYX_VALIGN_BOTTOM);
3842                         break;
3843
3844                 case Tabular::UNSET_ROTATE_TABULAR:
3845                         status.setOnOff(!tabular.rotate);
3846                         break;
3847
3848                 case Tabular::TOGGLE_ROTATE_CELL:
3849                 case Tabular::SET_ROTATE_CELL:
3850                         status.setOnOff(!oneCellHasRotationState(false,
3851                                 sel_row_start, sel_row_end, sel_col_start, sel_col_end));
3852                         break;
3853
3854                 case Tabular::UNSET_ROTATE_CELL:
3855                         status.setOnOff(!oneCellHasRotationState(true,
3856                                 sel_row_start, sel_row_end, sel_col_start, sel_col_end));
3857                         break;
3858
3859                 case Tabular::SET_USEBOX:
3860                         status.setOnOff(convert<int>(argument) == tabular.getUsebox(cur.idx()));
3861                         break;
3862
3863                 case Tabular::SET_LTFIRSTHEAD:
3864                         status.setOnOff(tabular.getRowOfLTHead(sel_row_start, dummyltt));
3865                         break;
3866
3867                 case Tabular::UNSET_LTFIRSTHEAD:
3868                         status.setOnOff(!tabular.getRowOfLTHead(sel_row_start, dummyltt));
3869                         break;
3870
3871                 case Tabular::SET_LTHEAD:
3872                         status.setOnOff(tabular.getRowOfLTHead(sel_row_start, dummyltt));
3873                         break;
3874
3875                 case Tabular::UNSET_LTHEAD:
3876                         status.setOnOff(!tabular.getRowOfLTHead(sel_row_start, dummyltt));
3877                         break;
3878
3879                 case Tabular::SET_LTFOOT:
3880                         status.setOnOff(tabular.getRowOfLTFoot(sel_row_start, dummyltt));
3881                         break;
3882
3883                 case Tabular::UNSET_LTFOOT:
3884                         status.setOnOff(!tabular.getRowOfLTFoot(sel_row_start, dummyltt));
3885                         break;
3886
3887                 case Tabular::SET_LTLASTFOOT:
3888                         status.setOnOff(tabular.getRowOfLTFoot(sel_row_start, dummyltt));
3889                         break;
3890
3891                 case Tabular::UNSET_LTLASTFOOT:
3892                         status.setOnOff(!tabular.getRowOfLTFoot(sel_row_start, dummyltt));
3893                         break;
3894
3895                 case Tabular::SET_LTNEWPAGE:
3896                         status.setOnOff(tabular.getLTNewPage(sel_row_start));
3897                         break;
3898
3899                 case Tabular::TOGGLE_LTCAPTION:
3900                         status.setEnabled(sel_row_start == sel_row_end);
3901                         status.setOnOff(tabular.ltCaption(sel_row_start));
3902                         break;
3903
3904                 case Tabular::SET_BOOKTABS:
3905                         status.setOnOff(tabular.use_booktabs);
3906                         break;
3907
3908                 case Tabular::UNSET_BOOKTABS:
3909                         status.setOnOff(!tabular.use_booktabs);
3910                         break;
3911
3912                 default:
3913                         status.clear();
3914                         status.setEnabled(false);
3915                         break;
3916                 }
3917                 return true;
3918         }
3919
3920         // These are only enabled inside tabular
3921         case LFUN_CELL_BACKWARD:
3922         case LFUN_CELL_FORWARD:
3923                 status.setEnabled(true);
3924                 return true;
3925
3926         // disable these with multiple cells selected
3927         case LFUN_INSET_INSERT:
3928         case LFUN_TABULAR_INSERT:
3929         case LFUN_FLEX_INSERT:
3930         case LFUN_FLOAT_INSERT:
3931         case LFUN_FLOAT_WIDE_INSERT:
3932         case LFUN_FOOTNOTE_INSERT:
3933         case LFUN_MARGINALNOTE_INSERT:
3934         case LFUN_MATH_INSERT:
3935         case LFUN_MATH_MODE:
3936         case LFUN_MATH_MUTATE:
3937         case LFUN_MATH_DISPLAY:
3938         case LFUN_NOTE_INSERT:
3939         case LFUN_OPTIONAL_INSERT:
3940         case LFUN_BOX_INSERT:
3941         case LFUN_BRANCH_INSERT:
3942         case LFUN_PHANTOM_INSERT:
3943         case LFUN_WRAP_INSERT:
3944         case LFUN_ERT_INSERT: {
3945                 if (cur.selIsMultiCell()) {
3946                         status.setEnabled(false);
3947                         return true;
3948                 } else
3949                         return cell(cur.idx())->getStatus(cur, cmd, status);
3950         }
3951
3952         // disable in non-fixed-width cells
3953         case LFUN_NEWLINE_INSERT:
3954         case LFUN_BREAK_PARAGRAPH: {
3955                 if (tabular.getPWidth(cur.idx()).zero()) {
3956                         status.setEnabled(false);
3957                         return true;
3958                 } else
3959                         return cell(cur.idx())->getStatus(cur, cmd, status);
3960         }
3961
3962         case LFUN_NEWPAGE_INSERT:
3963                 status.setEnabled(false);
3964                 return true;
3965
3966         case LFUN_PASTE:
3967                 if (cur.selIsMultiCell()) {
3968                         status.setEnabled(false);
3969                         status.message(_("You cannot paste into a multicell selection."));
3970                         return true;
3971                 }
3972                 if (tabularStackDirty() && theClipboard().isInternal()) {
3973                         status.setEnabled(true);
3974                         return true;
3975                 } 
3976                 return cell(cur.idx())->getStatus(cur, cmd, status);
3977
3978         case LFUN_INSET_MODIFY:
3979                 if (insetCode(cmd.getArg(0)) == TABULAR_CODE) {
3980                         status.setEnabled(true);
3981                         return true;
3982                 }
3983                 // Fall through
3984
3985         default:
3986                 // we try to handle this event in the insets dispatch function.
3987                 return cell(cur.idx())->getStatus(cur, cmd, status);
3988         }
3989 }
3990
3991
3992 int InsetTabular::latex(odocstream & os, OutputParams const & runparams) const
3993 {
3994         return tabular.latex(os, runparams);
3995 }
3996
3997
3998 int InsetTabular::plaintext(odocstream & os, OutputParams const & runparams) const
3999 {
4000         os << '\n'; // output table on a new line
4001         int const dp = runparams.linelen > 0 ? runparams.depth : 0;
4002         tabular.plaintext(os, runparams, dp, false, 0);
4003         return PLAINTEXT_NEWLINE;
4004 }
4005
4006
4007 int InsetTabular::docbook(odocstream & os, OutputParams const & runparams) const
4008 {
4009         int ret = 0;
4010         Inset * master = 0;
4011
4012         // FIXME: Why not pass a proper DocIterator here?
4013 #if 0
4014         // if the table is inside a float it doesn't need the informaltable
4015         // wrapper. Search for it.
4016         for (master = owner(); master; master = master->owner())
4017                 if (master->lyxCode() == FLOAT_CODE)
4018                         break;
4019 #endif
4020
4021         if (!master) {
4022                 os << "<informaltable>";
4023                 ++ret;
4024         }
4025         ret += tabular.docbook(os, runparams);
4026         if (!master) {
4027                 os << "</informaltable>";
4028                 ++ret;
4029         }
4030         return ret;
4031 }
4032
4033
4034 void InsetTabular::validate(LaTeXFeatures & features) const
4035 {
4036         tabular.validate(features);
4037 }
4038
4039
4040 shared_ptr<InsetTableCell const> InsetTabular::cell(idx_type idx) const
4041 {
4042         return tabular.cellInset(idx);
4043 }
4044
4045
4046 shared_ptr<InsetTableCell> InsetTabular::cell(idx_type idx)
4047 {
4048         return tabular.cellInset(idx);
4049 }
4050
4051
4052 void InsetTabular::cursorPos(BufferView const & bv,
4053                 CursorSlice const & sl, bool boundary, int & x, int & y) const
4054 {
4055         cell(sl.idx())->cursorPos(bv, sl, boundary, x, y);
4056
4057         // y offset     correction
4058         int const row = tabular.cellRow(sl.idx());
4059         for (int i = 0; i <= row; ++i) {
4060                 if (i != 0) {
4061                         y += tabular.rowAscent(i);
4062                         y += tabular.getAdditionalHeight(i);
4063                 }
4064                 if (i != row)
4065                         y += tabular.rowDescent(i);
4066         }
4067
4068         // x offset correction
4069         int const col = tabular.cellColumn(sl.idx());
4070         int idx = tabular.cellIndex(row, 0);
4071         for (int j = 0; j < col; ++j) {
4072                 if (tabular.isPartOfMultiColumn(row, j))
4073                         continue;
4074                 x += tabular.columnWidth(idx);
4075                 ++idx;
4076         }
4077         x += tabular.getBeginningOfTextInCell(idx);
4078         x += ADD_TO_TABULAR_WIDTH;
4079         x += scx_;
4080 }
4081
4082
4083 int InsetTabular::dist(BufferView & bv, idx_type const cell, int x, int y) const
4084 {
4085         int xx = 0;
4086         int yy = 0;
4087         Inset const & inset = *tabular.cellInset(cell);
4088         Point o = bv.coordCache().getInsets().xy(&inset);
4089         int const xbeg = o.x_ - tabular.getBeginningOfTextInCell(cell);
4090         int const xend = xbeg + tabular.columnWidth(cell);
4091         row_type const row = tabular.cellRow(cell);
4092         int const ybeg = o.y_ - tabular.rowAscent(row) -
4093                          tabular.getAdditionalHeight(row);
4094         int const yend = o.y_ + tabular.rowDescent(row);
4095
4096         if (x < xbeg)
4097                 xx = xbeg - x;
4098         else if (x > xend)
4099                 xx = x - xend;
4100
4101         if (y < ybeg)
4102                 yy = ybeg - y;
4103         else if (y > yend)
4104                 yy = y - yend;
4105
4106         //lyxerr << " xbeg=" << xbeg << "  xend=" << xend
4107         //       << " ybeg=" << ybeg << " yend=" << yend
4108         //       << " xx=" << xx << " yy=" << yy
4109         //       << " dist=" << xx + yy << endl;
4110         return xx + yy;
4111 }
4112
4113
4114 Inset * InsetTabular::editXY(Cursor & cur, int x, int y)
4115 {
4116         //lyxerr << "InsetTabular::editXY: " << this << endl;
4117         cur.setSelection(false);
4118         cur.push(*this);
4119         cur.idx() = getNearestCell(cur.bv(), x, y);
4120         resetPos(cur);
4121         return cur.bv().textMetrics(&cell(cur.idx())->text()).editXY(cur, x, y);
4122 }
4123
4124
4125 void InsetTabular::setCursorFromCoordinates(Cursor & cur, int x, int y) const
4126 {
4127         cur.idx() = getNearestCell(cur.bv(), x, y);
4128         cur.bv().textMetrics(&cell(cur.idx())->text()).setCursorFromCoordinates(cur, x, y);
4129 }
4130
4131
4132 InsetTabular::idx_type InsetTabular::getNearestCell(BufferView & bv, int x, int y) const
4133 {
4134         idx_type idx_min = 0;
4135         int dist_min = numeric_limits<int>::max();
4136         for (idx_type i = 0, n = nargs(); i != n; ++i) {
4137                 if (bv.coordCache().getInsets().has(tabular.cellInset(i).get())) {
4138                         int const d = dist(bv, i, x, y);
4139                         if (d < dist_min) {
4140                                 dist_min = d;
4141                                 idx_min = i;
4142                         }
4143                 }
4144         }
4145         return idx_min;
4146 }
4147
4148
4149 int InsetTabular::cellXPos(idx_type const cell) const
4150 {
4151         idx_type c = cell;
4152
4153         for (; !tabular.isFirstCellInRow(c); --c)
4154                 ;
4155         int lx = 0;
4156         for (; c < cell; ++c)
4157                 lx += tabular.columnWidth(c);
4158
4159         return lx;
4160 }
4161
4162
4163 void InsetTabular::resetPos(Cursor & cur) const
4164 {
4165         BufferView & bv = cur.bv();
4166         int const maxwidth = bv.workWidth();
4167
4168         int const scx_old = scx_;
4169         int const i = cur.find(this);
4170         if (i == -1) {
4171                 scx_ = 0;
4172         } else {
4173                 int const X1 = 0;
4174                 int const X2 = maxwidth;
4175                 int const offset = ADD_TO_TABULAR_WIDTH + 2;
4176                 int const x1 = xo(cur.bv()) + cellXPos(cur[i].idx()) + offset;
4177                 int const x2 = x1 + tabular.columnWidth(cur[i].idx());
4178
4179                 if (x1 < X1)
4180                         scx_ = X1 + 20 - x1;
4181                 else if (x2 > X2)
4182                         scx_ = X2 - 20 - x2;
4183                 else
4184                         scx_ = 0;
4185         }
4186
4187         // only update if offset changed
4188         if (scx_ != scx_old)
4189                 cur.updateFlags(Update::Force | Update::FitCursor);
4190 }
4191
4192
4193 void InsetTabular::moveNextCell(Cursor & cur, EntryDirection entry_from)
4194 {
4195         if (isRightToLeft(cur)) {
4196                 if (tabular.isFirstCellInRow(cur.idx())) {
4197                         row_type const row = tabular.cellRow(cur.idx());
4198                         if (row == tabular.row_info.size() - 1)
4199                                 return;
4200                         cur.idx() = tabular.cellBelow(tabular.getLastCellInRow(row));
4201                 } else {
4202                         if (cur.idx() == 0)
4203                                 return;
4204                         --cur.idx();
4205                 }
4206         } else {
4207                 if (tabular.isLastCell(cur.idx()))
4208                         return;
4209                 ++cur.idx();
4210         }
4211
4212         cur.boundary(false);
4213
4214         if (cur.selIsMultiCell()) {
4215                 cur.pit() = cur.lastpit();
4216                 cur.pos() = cur.lastpos();
4217                 resetPos(cur);
4218                 return;
4219         }
4220
4221         cur.pit() = 0;
4222         cur.pos() = 0;
4223
4224         // in visual mode, place cursor at extreme left or right
4225         
4226         switch(entry_from) {
4227
4228         case ENTRY_DIRECTION_RIGHT:
4229                 cur.posVisToRowExtremity(false /* !left */);
4230                 break;
4231         case ENTRY_DIRECTION_LEFT:
4232                 cur.posVisToRowExtremity(true /* left */);
4233                 break;
4234         case ENTRY_DIRECTION_IGNORE:
4235                 // nothing to do in this case
4236                 break;
4237
4238         }
4239
4240         resetPos(cur);
4241 }
4242
4243
4244 void InsetTabular::movePrevCell(Cursor & cur, EntryDirection entry_from)
4245 {
4246         if (isRightToLeft(cur)) {
4247                 if (tabular.isLastCellInRow(cur.idx())) {
4248                         row_type const row = tabular.cellRow(cur.idx());
4249                         if (row == 0)
4250                                 return;
4251                         cur.idx() = tabular.getFirstCellInRow(row);
4252                         cur.idx() = tabular.cellAbove(cur.idx());
4253                 } else {
4254                         if (tabular.isLastCell(cur.idx()))
4255                                 return;
4256                         ++cur.idx();
4257                 }
4258         } else {
4259                 if (cur.idx() == 0) // first cell
4260                         return;
4261                 --cur.idx();
4262         }
4263
4264         if (cur.selIsMultiCell()) {
4265                 cur.pit() = cur.lastpit();
4266                 cur.pos() = cur.lastpos();
4267                 resetPos(cur);
4268                 return;
4269         }
4270
4271         cur.pit() = cur.lastpit();
4272         cur.pos() = cur.lastpos();
4273
4274         // in visual mode, place cursor at extreme left or right
4275         
4276         switch(entry_from) {
4277
4278         case ENTRY_DIRECTION_RIGHT:
4279                 cur.posVisToRowExtremity(false /* !left */);
4280                 break;
4281         case ENTRY_DIRECTION_LEFT:
4282                 cur.posVisToRowExtremity(true /* left */);
4283                 break;
4284         case ENTRY_DIRECTION_IGNORE:
4285                 // nothing to do in this case
4286                 break;
4287
4288         }
4289
4290         resetPos(cur);
4291 }
4292
4293
4294 bool InsetTabular::tabularFeatures(Cursor & cur, string const & what)
4295 {
4296         Tabular::Feature action = Tabular::LAST_ACTION;
4297
4298         int i = 0;
4299         for (; tabularFeature[i].action != Tabular::LAST_ACTION; ++i) {
4300                 string const tmp = tabularFeature[i].feature;
4301
4302                 if (tmp == what.substr(0, tmp.length())) {
4303                         //if (!compare(tabularFeatures[i].feature.c_str(), what.c_str(),
4304                         //tabularFeatures[i].feature.length()))
4305                         action = tabularFeature[i].action;
4306                         break;
4307                 }
4308         }
4309         if (action == Tabular::LAST_ACTION)
4310                 return false;
4311
4312         string const val =
4313                 ltrim(what.substr(tabularFeature[i].feature.length()));
4314         tabularFeatures(cur, action, val);
4315         return true;
4316 }
4317
4318
4319 static void checkLongtableSpecial(Tabular::ltType & ltt,
4320                           string const & special, bool & flag)
4321 {
4322         if (special == "dl_above") {
4323                 ltt.topDL = flag;
4324                 ltt.set = false;
4325         } else if (special == "dl_below") {
4326                 ltt.bottomDL = flag;
4327                 ltt.set = false;
4328         } else if (special == "empty") {
4329                 ltt.empty = flag;
4330                 ltt.set = false;
4331         } else if (flag) {
4332                 ltt.empty = false;
4333                 ltt.set = true;
4334         }
4335 }
4336
4337 bool InsetTabular::oneCellHasRotationState(bool rotated,
4338                 row_type row_start, row_type row_end,
4339                 col_type col_start, col_type col_end) const {
4340
4341         for (row_type i = row_start; i <= row_end; ++i) {
4342                 for (col_type j = col_start; j <= col_end; ++j) {
4343                         if (tabular.getRotateCell(tabular.cellIndex(i, j))
4344                                 == rotated) {
4345                                 return true;
4346                         }
4347                 }
4348         }
4349         return false;
4350 }
4351
4352 void InsetTabular::tabularFeatures(Cursor & cur,
4353         Tabular::Feature feature, string const & value)
4354 {
4355         col_type sel_col_start;
4356         col_type sel_col_end;
4357         row_type sel_row_start;
4358         row_type sel_row_end;
4359         bool setLines = false;
4360         LyXAlignment setAlign = LYX_ALIGN_LEFT;
4361         Tabular::VAlignment setVAlign = Tabular::LYX_VALIGN_TOP;
4362
4363         switch (feature) {
4364
4365         case Tabular::M_ALIGN_LEFT:
4366         case Tabular::ALIGN_LEFT:
4367                 setAlign = LYX_ALIGN_LEFT;
4368                 break;
4369
4370         case Tabular::M_ALIGN_RIGHT:
4371         case Tabular::ALIGN_RIGHT:
4372                 setAlign = LYX_ALIGN_RIGHT;
4373                 break;
4374
4375         case Tabular::M_ALIGN_CENTER:
4376         case Tabular::ALIGN_CENTER:
4377                 setAlign = LYX_ALIGN_CENTER;
4378                 break;
4379
4380         case Tabular::ALIGN_BLOCK:
4381                 setAlign = LYX_ALIGN_BLOCK;
4382                 break;
4383
4384         case Tabular::M_VALIGN_TOP:
4385         case Tabular::VALIGN_TOP:
4386                 setVAlign = Tabular::LYX_VALIGN_TOP;
4387                 break;
4388
4389         case Tabular::M_VALIGN_BOTTOM:
4390         case Tabular::VALIGN_BOTTOM:
4391                 setVAlign = Tabular::LYX_VALIGN_BOTTOM;
4392                 break;
4393
4394         case Tabular::M_VALIGN_MIDDLE:
4395         case Tabular::VALIGN_MIDDLE:
4396                 setVAlign = Tabular::LYX_VALIGN_MIDDLE;
4397                 break;
4398
4399         default:
4400                 break;
4401         }
4402
4403         cur.recordUndoInset(ATOMIC_UNDO);
4404
4405         getSelection(cur, sel_row_start, sel_row_end, sel_col_start, sel_col_end);
4406         row_type const row = tabular.cellRow(cur.idx());
4407         col_type const column = tabular.cellColumn(cur.idx());
4408         bool flag = true;
4409         Tabular::ltType ltt;
4410
4411         switch (feature) {
4412
4413         case Tabular::SET_PWIDTH: {
4414                 Length const len(value);
4415                 tabular.setColumnPWidth(cur, cur.idx(), len);
4416                 if (len.zero()
4417                     && tabular.getAlignment(cur.idx(), true) == LYX_ALIGN_BLOCK)
4418                         tabularFeatures(cur, Tabular::ALIGN_CENTER, string());
4419                 break;
4420         }
4421
4422         case Tabular::SET_MPWIDTH:
4423                 tabular.setMColumnPWidth(cur, cur.idx(), Length(value));
4424                 break;
4425
4426         case Tabular::SET_SPECIAL_COLUMN:
4427         case Tabular::SET_SPECIAL_MULTI:
4428                 tabular.setAlignSpecial(cur.idx(), from_utf8(value), feature);
4429                 break;
4430
4431         case Tabular::APPEND_ROW:
4432                 // append the row into the tabular
4433                 tabular.appendRow(cur.idx());
4434                 break;
4435
4436         case Tabular::APPEND_COLUMN:
4437                 // append the column into the tabular
4438                 tabular.appendColumn(cur.idx());
4439                 cur.idx() = tabular.cellIndex(row, column);
4440                 break;
4441
4442         case Tabular::DELETE_ROW:
4443                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4444                         tabular.deleteRow(sel_row_start);
4445                 if (sel_row_start >= tabular.row_info.size())
4446                         --sel_row_start;
4447                 cur.idx() = tabular.cellIndex(sel_row_start, column);
4448                 cur.pit() = 0;
4449                 cur.pos() = 0;
4450                 cur.setSelection(false);
4451                 break;
4452
4453         case Tabular::DELETE_COLUMN:
4454                 for (col_type i = sel_col_start; i <= sel_col_end; ++i)
4455                         tabular.deleteColumn(sel_col_start);
4456                 if (sel_col_start >= tabular.column_info.size())
4457                         --sel_col_start;
4458                 cur.idx() = tabular.cellIndex(row, sel_col_start);
4459                 cur.pit() = 0;
4460                 cur.pos() = 0;
4461                 cur.setSelection(false);
4462                 break;
4463
4464         case Tabular::COPY_ROW:
4465                 tabular.copyRow(row);
4466                 break;
4467
4468         case Tabular::COPY_COLUMN:
4469                 tabular.copyColumn(column);
4470                 cur.idx() = tabular.cellIndex(row, column);
4471                 break;
4472
4473         case Tabular::TOGGLE_LINE_TOP: {
4474                 bool lineSet = !tabular.topLine(cur.idx());
4475                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4476                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
4477                                 tabular.setTopLine(tabular.cellIndex(i, j), lineSet);
4478                 break;
4479         }
4480
4481         case Tabular::TOGGLE_LINE_BOTTOM: {
4482                 bool lineSet = !tabular.bottomLine(cur.idx());
4483                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4484                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
4485                                 tabular.setBottomLine(tabular.cellIndex(i, j), lineSet);
4486                 break;
4487         }
4488
4489         case Tabular::TOGGLE_LINE_LEFT: {
4490                 bool lineSet = !tabular.leftLine(cur.idx());
4491                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4492                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
4493                                 tabular.setLeftLine(tabular.cellIndex(i, j), lineSet);
4494                 break;
4495         }
4496
4497         case Tabular::TOGGLE_LINE_RIGHT: {
4498                 bool lineSet = !tabular.rightLine(cur.idx());
4499                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4500                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
4501                                 tabular.setRightLine(tabular.cellIndex(i, j), lineSet);
4502                 break;
4503         }
4504
4505         case Tabular::M_ALIGN_LEFT:
4506         case Tabular::M_ALIGN_RIGHT:
4507         case Tabular::M_ALIGN_CENTER:
4508                 flag = false;
4509         case Tabular::ALIGN_LEFT:
4510         case Tabular::ALIGN_RIGHT:
4511         case Tabular::ALIGN_CENTER:
4512         case Tabular::ALIGN_BLOCK:
4513                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4514                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
4515                                 tabular.setAlignment(tabular.cellIndex(i, j), setAlign, flag);
4516                 break;
4517
4518         case Tabular::M_VALIGN_TOP:
4519         case Tabular::M_VALIGN_BOTTOM:
4520         case Tabular::M_VALIGN_MIDDLE:
4521                 flag = false;
4522         case Tabular::VALIGN_TOP:
4523         case Tabular::VALIGN_BOTTOM:
4524         case Tabular::VALIGN_MIDDLE:
4525                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4526                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
4527                                 tabular.setVAlignment(tabular.cellIndex(i, j), setVAlign, flag);
4528                 break;
4529
4530         case Tabular::MULTICOLUMN: {
4531                 if (!cur.selection()) {
4532                         // just multicol for one single cell
4533                         // check whether we are completely in a multicol
4534                         if (tabular.isMultiColumn(cur.idx()))
4535                                 tabular.unsetMultiColumn(cur.idx());
4536                         else
4537                                 tabular.setMultiColumn(cur.idx(), 1);
4538                         break;
4539                 }
4540                 // we have a selection so this means we just add all this
4541                 // cells to form a multicolumn cell
4542                 idx_type const s_start = cur.selBegin().idx();
4543                 idx_type const s_end = cur.selEnd().idx();
4544                 tabular.setMultiColumn(s_start, s_end - s_start + 1);
4545                 cur.idx() = s_start;
4546                 cur.pit() = 0;
4547                 cur.pos() = 0;
4548                 cur.setSelection(false);
4549                 break;
4550         }
4551
4552         case Tabular::SET_ALL_LINES:
4553                 setLines = true;
4554         case Tabular::UNSET_ALL_LINES:
4555                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4556                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
4557                                 tabular.setAllLines(
4558                                         tabular.cellIndex(i,j), setLines);
4559                 break;
4560
4561         case Tabular::SET_BORDER_LINES:
4562                 for (row_type i = sel_row_start; i <= sel_row_end; ++i) {
4563                         tabular.setLeftLine(tabular.cellIndex(i, sel_col_start), true);
4564                         tabular.setRightLine(tabular.cellIndex(i, sel_col_end), true);
4565                 }
4566                 for (col_type j = sel_col_start; j <= sel_col_end; ++j) {
4567                         tabular.setTopLine(tabular.cellIndex(sel_row_start, j), true);
4568                         tabular.setBottomLine(tabular.cellIndex(sel_row_end, j), true);
4569                 }
4570                 break;
4571
4572         case Tabular::SET_LONGTABULAR:
4573                 tabular.is_long_tabular = true;
4574                 break;
4575
4576         case Tabular::UNSET_LONGTABULAR:
4577                 tabular.is_long_tabular = false;
4578                 break;
4579
4580         case Tabular::SET_ROTATE_TABULAR:
4581                 tabular.rotate = true;
4582                 break;
4583
4584         case Tabular::UNSET_ROTATE_TABULAR:
4585                 tabular.rotate = false;
4586                 break;
4587
4588         case Tabular::TOGGLE_ROTATE_TABULAR:
4589                 tabular.rotate = !tabular.rotate;
4590                 break;
4591
4592         case Tabular::TABULAR_VALIGN_TOP:
4593                 tabular.tabular_valignment = Tabular::LYX_VALIGN_TOP;
4594                 break;
4595
4596         case Tabular::TABULAR_VALIGN_MIDDLE:
4597                 tabular.tabular_valignment = Tabular::LYX_VALIGN_MIDDLE;
4598                 break;
4599
4600         case Tabular::TABULAR_VALIGN_BOTTOM:
4601                 tabular.tabular_valignment = Tabular::LYX_VALIGN_BOTTOM;
4602                 break;
4603
4604         case Tabular::SET_ROTATE_CELL:
4605                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4606                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
4607                                 tabular.setRotateCell(
4608                                         tabular.cellIndex(i, j), true);
4609                 break;
4610
4611         case Tabular::UNSET_ROTATE_CELL:
4612                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4613                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
4614                                 tabular.setRotateCell(tabular.cellIndex(i, j), false);
4615                 break;
4616
4617         case Tabular::TOGGLE_ROTATE_CELL:
4618                 {
4619                 bool oneNotRotated = oneCellHasRotationState(false,
4620                         sel_row_start, sel_row_end, sel_col_start, sel_col_end);
4621
4622                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4623                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
4624                                 tabular.setRotateCell(tabular.cellIndex(i, j),
4625                                                                           oneNotRotated);
4626                 }
4627                 break;
4628
4629         case Tabular::SET_USEBOX: {
4630                 Tabular::BoxType val = Tabular::BoxType(convert<int>(value));
4631                 if (val == tabular.getUsebox(cur.idx()))
4632                         val = Tabular::BOX_NONE;
4633                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4634                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
4635                                 tabular.setUsebox(tabular.cellIndex(i, j), val);
4636                 break;
4637         }
4638
4639         case Tabular::UNSET_LTFIRSTHEAD:
4640                 flag = false;
4641         case Tabular::SET_LTFIRSTHEAD:
4642                 tabular.getRowOfLTFirstHead(row, ltt);
4643                 checkLongtableSpecial(ltt, value, flag);
4644                 tabular.setLTHead(row, flag, ltt, true);
4645                 break;
4646
4647         case Tabular::UNSET_LTHEAD:
4648                 flag = false;
4649         case Tabular::SET_LTHEAD:
4650                 tabular.getRowOfLTHead(row, ltt);
4651                 checkLongtableSpecial(ltt, value, flag);
4652                 tabular.setLTHead(row, flag, ltt, false);
4653                 break;
4654
4655         case Tabular::UNSET_LTFOOT:
4656                 flag = false;
4657         case Tabular::SET_LTFOOT:
4658                 tabular.getRowOfLTFoot(row, ltt);
4659                 checkLongtableSpecial(ltt, value, flag);
4660                 tabular.setLTFoot(row, flag, ltt, false);
4661                 break;
4662
4663         case Tabular::UNSET_LTLASTFOOT:
4664                 flag = false;
4665         case Tabular::SET_LTLASTFOOT:
4666                 tabular.getRowOfLTLastFoot(row, ltt);
4667                 checkLongtableSpecial(ltt, value, flag);
4668                 tabular.setLTFoot(row, flag, ltt, true);
4669                 break;
4670
4671         case Tabular::SET_LTNEWPAGE:
4672                 tabular.setLTNewPage(row, !tabular.getLTNewPage(row));
4673                 break;
4674
4675         case Tabular::TOGGLE_LTCAPTION:
4676                 cur.idx() = tabular.setLTCaption(row, !tabular.ltCaption(row));
4677                 cur.pit() = 0;
4678                 cur.pos() = 0;
4679                 cur.setSelection(false);
4680                 break;
4681
4682         case Tabular::SET_BOOKTABS:
4683                 tabular.use_booktabs = true;
4684                 break;
4685
4686         case Tabular::UNSET_BOOKTABS:
4687                 tabular.use_booktabs = false;
4688                 break;
4689
4690         case Tabular::SET_TOP_SPACE: {
4691                 Length len;
4692                 if (value == "default")
4693                         for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4694                                 tabular.row_info[i].top_space_default = true;
4695                 else if (isValidLength(value, &len))
4696                         for (row_type i = sel_row_start; i <= sel_row_end; ++i) {
4697                                 tabular.row_info[i].top_space_default = false;
4698                                 tabular.row_info[i].top_space = len;
4699                         }
4700                 else
4701                         for (row_type i = sel_row_start; i <= sel_row_end; ++i) {
4702                                 tabular.row_info[i].top_space_default = false;
4703                                 tabular.row_info[i].top_space = len;
4704                         }
4705                 break;
4706         }
4707
4708         case Tabular::SET_BOTTOM_SPACE: {
4709                 Length len;
4710                 if (value == "default")
4711                         for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4712                                 tabular.row_info[i].bottom_space_default = true;
4713                 else if (isValidLength(value, &len))
4714                         for (row_type i = sel_row_start; i <= sel_row_end; ++i) {
4715                                 tabular.row_info[i].bottom_space_default = false;
4716                                 tabular.row_info[i].bottom_space = len;
4717                         }
4718                 else
4719                         for (row_type i = sel_row_start; i <= sel_row_end; ++i) {
4720                                 tabular.row_info[i].bottom_space_default = false;
4721                                 tabular.row_info[i].bottom_space = len;
4722                         }
4723                 break;
4724         }
4725
4726         case Tabular::SET_INTERLINE_SPACE: {
4727                 Length len;
4728                 if (value == "default")
4729                         for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4730                                 tabular.row_info[i].interline_space_default = true;
4731                 else if (isValidLength(value, &len))
4732                         for (row_type i = sel_row_start; i <= sel_row_end; ++i) {
4733                                 tabular.row_info[i].interline_space_default = false;
4734                                 tabular.row_info[i].interline_space = len;
4735                         }
4736                 else
4737                         for (row_type i = sel_row_start; i <= sel_row_end; ++i) {
4738                                 tabular.row_info[i].interline_space_default = false;
4739                                 tabular.row_info[i].interline_space = len;
4740                         }
4741                 break;
4742         }
4743
4744         // dummy stuff just to avoid warnings
4745         case Tabular::LAST_ACTION:
4746                 break;
4747         }
4748 }
4749
4750
4751 bool InsetTabular::showInsetDialog(BufferView * bv) const
4752 {
4753         bv->showDialog("tabular", params2string(*this),
4754                 const_cast<InsetTabular *>(this));
4755         return true;
4756 }
4757
4758
4759 void InsetTabular::openLayoutDialog(BufferView * bv) const
4760 {
4761         bv->showDialog("tabular", params2string(*this),
4762                 const_cast<InsetTabular *>(this));
4763 }
4764
4765
4766 bool InsetTabular::copySelection(Cursor & cur)
4767 {
4768         if (!cur.selection())
4769                 return false;
4770
4771         row_type rs, re;
4772         col_type cs, ce;
4773         getSelection(cur, rs, re, cs, ce);
4774
4775         paste_tabular.reset(new Tabular(tabular));
4776
4777         for (row_type i = 0; i < rs; ++i)
4778                 paste_tabular->deleteRow(0);
4779
4780         row_type const rows = re - rs + 1;
4781         while (paste_tabular->row_info.size() > rows)
4782                 paste_tabular->deleteRow(rows);
4783
4784         for (col_type i = 0; i < cs; ++i)
4785                 paste_tabular->deleteColumn(0);
4786
4787         col_type const columns = ce - cs + 1;
4788         while (paste_tabular->column_info.size() > columns)
4789                 paste_tabular->deleteColumn(columns);
4790
4791         paste_tabular->setBuffer(tabular.buffer());
4792
4793         odocstringstream os;
4794         OutputParams const runparams(0);
4795         paste_tabular->plaintext(os, runparams, 0, true, '\t');
4796         // Needed for the "Edit->Paste recent" menu and the system clipboard.
4797         cap::copySelection(cur, os.str());
4798
4799         // mark tabular stack dirty
4800         // FIXME: this is a workaround for bug 1919. Should be removed for 1.5,
4801         // when we (hopefully) have a one-for-all paste mechanism.
4802         // This must be called after cap::copySelection.
4803         dirtyTabularStack(true);
4804
4805         return true;
4806 }
4807
4808
4809 bool InsetTabular::pasteClipboard(Cursor & cur)
4810 {
4811         if (!paste_tabular)
4812                 return false;
4813         col_type const actcol = tabular.cellColumn(cur.idx());
4814         row_type const actrow = tabular.cellRow(cur.idx());
4815         for (row_type r1 = 0, r2 = actrow;
4816              r1 < paste_tabular->row_info.size() && r2 < tabular.row_info.size();
4817              ++r1, ++r2) {
4818                 for (col_type c1 = 0, c2 = actcol;
4819                     c1 < paste_tabular->column_info.size() && c2 < tabular.column_info.size();
4820                     ++c1, ++c2) {
4821                         if (paste_tabular->isPartOfMultiColumn(r1, c1) &&
4822                             tabular.isPartOfMultiColumn(r2, c2))
4823                                 continue;
4824                         if (paste_tabular->isPartOfMultiColumn(r1, c1)) {
4825                                 --c2;
4826                                 continue;
4827                         }
4828                         if (tabular.isPartOfMultiColumn(r2, c2)) {
4829                                 --c1;
4830                                 continue;
4831                         }
4832                         shared_ptr<InsetTableCell> inset(
4833                                 new InsetTableCell(*paste_tabular->cellInset(r1, c1)));
4834                         tabular.setCellInset(r2, c2, inset);
4835                         // FIXME: change tracking (MG)
4836                         inset->setChange(Change(buffer().params().trackChanges ?
4837                                                 Change::INSERTED : Change::UNCHANGED));
4838                         cur.pos() = 0;
4839                 }
4840         }
4841         return true;
4842 }
4843
4844
4845 void InsetTabular::cutSelection(Cursor & cur)
4846 {
4847         if (!cur.selection())
4848                 return;
4849
4850         row_type rs, re;
4851         col_type cs, ce;
4852         getSelection(cur, rs, re, cs, ce);
4853         for (row_type i = rs; i <= re; ++i) {
4854                 for (col_type j = cs; j <= ce; ++j) {
4855                         shared_ptr<InsetTableCell> t
4856                                 = cell(tabular.cellIndex(i, j));
4857                         if (buffer().params().trackChanges)
4858                                 // FIXME: Change tracking (MG)
4859                                 t->setChange(Change(Change::DELETED));
4860                         else
4861                                 t->clear();
4862                 }
4863         }
4864
4865         // cursor position might be invalid now
4866         if (cur.pit() > cur.lastpit())
4867                 cur.pit() = cur.lastpit();
4868         if (cur.pos() > cur.lastpos())
4869                 cur.pos() = cur.lastpos();
4870         cur.clearSelection();
4871 }
4872
4873
4874 bool InsetTabular::isRightToLeft(Cursor & cur) const
4875 {
4876         LASSERT(cur.depth() > 1, /**/);
4877         Paragraph const & parentpar = cur[cur.depth() - 2].paragraph();
4878         pos_type const parentpos = cur[cur.depth() - 2].pos();
4879         return parentpar.getFontSettings(buffer().params(),
4880                                          parentpos).language()->rightToLeft();
4881 }
4882
4883 docstring InsetTabular::asString(idx_type stidx, idx_type enidx, 
4884                                  bool intoInsets)
4885 {
4886         LASSERT(stidx <= enidx, return docstring());
4887         docstring retval;
4888         col_type const col1 = tabular.cellColumn(stidx);
4889         col_type const col2 = tabular.cellColumn(enidx);
4890         row_type const row1 = tabular.cellRow(stidx);
4891         row_type const row2 = tabular.cellRow(enidx);
4892         bool first = true;
4893         for (col_type col = col1; col <= col2; col++)
4894                 for (row_type row = row1; row <= row2; row++) {
4895                         if (!first)
4896                                 retval += "\n";
4897                         else
4898                                 first = false;
4899                         retval += tabular.cellInset(row, col)->asString(intoInsets);
4900                 }
4901         return retval;
4902 }
4903
4904
4905 void InsetTabular::getSelection(Cursor & cur,
4906         row_type & rs, row_type & re, col_type & cs, col_type & ce) const
4907 {
4908         CursorSlice const & beg = cur.selBegin();
4909         CursorSlice const & end = cur.selEnd();
4910         cs = tabular.cellColumn(beg.idx());
4911         ce = tabular.cellColumn(end.idx());
4912         if (cs > ce) {
4913                 ce = cs;
4914                 cs = tabular.cellColumn(end.idx());
4915         } else {
4916                 ce = tabular.cellRightColumn(end.idx());
4917         }
4918
4919         rs = tabular.cellRow(beg.idx());
4920         re = tabular.cellRow(end.idx());
4921         if (rs > re)
4922                 swap(rs, re);
4923 }
4924
4925
4926 Text * InsetTabular::getText(int idx) const
4927 {
4928         return size_t(idx) < nargs() ? cell(idx)->getText(0) : 0;
4929 }
4930
4931
4932 void InsetTabular::setChange(Change const & change)
4933 {
4934         for (idx_type idx = 0; idx < nargs(); ++idx)
4935                 cell(idx)->setChange(change);
4936 }
4937
4938
4939 void InsetTabular::acceptChanges(BufferParams const & bparams)
4940 {
4941         for (idx_type idx = 0; idx < nargs(); ++idx)
4942                 cell(idx)->acceptChanges(bparams);
4943 }
4944
4945
4946 void InsetTabular::rejectChanges(BufferParams const & bparams)
4947 {
4948         for (idx_type idx = 0; idx < nargs(); ++idx)
4949                 cell(idx)->rejectChanges(bparams);
4950 }
4951
4952
4953 bool InsetTabular::allowParagraphCustomization(idx_type cell) const
4954 {
4955         return tabular.getPWidth(cell).zero();
4956 }
4957
4958
4959 bool InsetTabular::forcePlainLayout(idx_type cell) const
4960 {
4961         return !tabular.getPWidth(cell).zero();
4962 }
4963
4964
4965 bool InsetTabular::insertPlaintextString(BufferView & bv, docstring const & buf,
4966                                      bool usePaste)
4967 {
4968         if (buf.length() <= 0)
4969                 return true;
4970
4971         col_type cols = 1;
4972         row_type rows = 1;
4973         col_type maxCols = 1;
4974         size_t const len = buf.length();
4975         size_t p = 0;
4976
4977         while (p < len &&
4978                (p = buf.find_first_of(from_ascii("\t\n"), p)) != docstring::npos) {
4979                 switch (buf[p]) {
4980                 case '\t':
4981                         ++cols;
4982                         break;
4983                 case '\n':
4984                         if (p + 1 < len)
4985                                 ++rows;
4986                         maxCols = max(cols, maxCols);
4987                         cols = 1;
4988                         break;
4989                 }
4990                 ++p;
4991         }
4992         maxCols = max(cols, maxCols);
4993         Tabular * loctab;
4994         idx_type cell = 0;
4995         col_type ocol = 0;
4996         row_type row = 0;
4997         if (usePaste) {
4998                 paste_tabular.reset(new Tabular(buffer(), rows, maxCols));
4999                 loctab = paste_tabular.get();
5000                 cols = 0;
5001                 dirtyTabularStack(true);
5002         } else {
5003                 loctab = &tabular;
5004                 cell = bv.cursor().idx();
5005                 ocol = tabular.cellColumn(cell);
5006                 row = tabular.cellRow(cell);
5007         }
5008
5009         size_t op = 0;
5010         idx_type const cells = loctab->numberofcells;
5011         p = 0;
5012         cols = ocol;
5013         rows = loctab->row_info.size();
5014         col_type const columns = loctab->column_info.size();
5015
5016         while (cell < cells && p < len && row < rows &&
5017                (p = buf.find_first_of(from_ascii("\t\n"), p)) != docstring::npos)
5018         {
5019                 if (p >= len)
5020                         break;
5021                 switch (buf[p]) {
5022                 case '\t':
5023                         // we can only set this if we are not too far right
5024                         if (cols < columns) {
5025                                 shared_ptr<InsetTableCell> inset = loctab->cellInset(cell);
5026                                 Font const font = bv.textMetrics(&inset->text()).
5027                                         displayFont(0, 0);
5028                                 inset->setText(buf.substr(op, p - op), font,
5029                                                buffer().params().trackChanges);
5030                                 ++cols;
5031                                 ++cell;
5032                         }
5033                         break;
5034                 case '\n':
5035                         // we can only set this if we are not too far right
5036                         if (cols < columns) {
5037                                 shared_ptr<InsetTableCell> inset = tabular.cellInset(cell);
5038                                 Font const font = bv.textMetrics(&inset->text()).
5039                                         displayFont(0, 0);
5040                                 inset->setText(buf.substr(op, p - op), font,
5041                                                buffer().params().trackChanges);
5042                         }
5043                         cols = ocol;
5044                         ++row;
5045                         if (row < rows)
5046                                 cell = loctab->cellIndex(row, cols);
5047                         break;
5048                 }
5049                 ++p;
5050                 op = p;
5051         }
5052         // check for the last cell if there is no trailing '\n'
5053         if (cell < cells && op < len) {
5054                 shared_ptr<InsetTableCell> inset = loctab->cellInset(cell);
5055                 Font const font = bv.textMetrics(&inset->text()).displayFont(0, 0);
5056                 inset->setText(buf.substr(op, len - op), font,
5057                         buffer().params().trackChanges);
5058         }
5059         return true;
5060 }
5061
5062
5063 void InsetTabular::addPreview(PreviewLoader & loader) const
5064 {
5065         row_type const rows = tabular.row_info.size();
5066         col_type const columns = tabular.column_info.size();
5067         for (row_type i = 0; i < rows; ++i) {
5068                 for (col_type j = 0; j < columns; ++j)
5069                         tabular.cellInset(i, j)->addPreview(loader);
5070         }
5071 }
5072
5073
5074 bool InsetTabular::completionSupported(Cursor const & cur) const
5075 {
5076         Cursor const & bvCur = cur.bv().cursor();
5077         if (&bvCur.inset() != this)
5078                 return false;
5079         return cur.text()->completionSupported(cur);
5080 }
5081
5082
5083 bool InsetTabular::inlineCompletionSupported(Cursor const & cur) const
5084 {
5085         return completionSupported(cur);
5086 }
5087
5088
5089 bool InsetTabular::automaticInlineCompletion() const
5090 {
5091         return lyxrc.completion_inline_text;
5092 }
5093
5094
5095 bool InsetTabular::automaticPopupCompletion() const
5096 {
5097         return lyxrc.completion_popup_text;
5098 }
5099
5100
5101 bool InsetTabular::showCompletionCursor() const
5102 {
5103         return lyxrc.completion_cursor_text;
5104 }
5105
5106
5107 CompletionList const * InsetTabular::createCompletionList(Cursor const & cur) const
5108 {
5109         return completionSupported(cur) ? cur.text()->createCompletionList(cur) : 0;
5110 }
5111
5112
5113 docstring InsetTabular::completionPrefix(Cursor const & cur) const
5114 {
5115         if (!completionSupported(cur))
5116                 return docstring();
5117         return cur.text()->completionPrefix(cur);
5118 }
5119
5120
5121 bool InsetTabular::insertCompletion(Cursor & cur, docstring const & s, bool finished)
5122 {
5123         if (!completionSupported(cur))
5124                 return false;
5125
5126         return cur.text()->insertCompletion(cur, s, finished);
5127 }
5128
5129
5130 void InsetTabular::completionPosAndDim(Cursor const & cur, int & x, int & y, 
5131                                     Dimension & dim) const
5132 {
5133         TextMetrics const & tm = cur.bv().textMetrics(cur.text());
5134         tm.completionPosAndDim(cur, x, y, dim);
5135 }
5136
5137
5138 void InsetTabular::string2params(string const & in, InsetTabular & inset)
5139 {
5140         istringstream data(in);
5141         Lexer lex;
5142         lex.setStream(data);
5143
5144         if (in.empty())
5145                 return;
5146
5147         string token;
5148         lex >> token;
5149         if (!lex || token != "tabular") {
5150                 LYXERR0("Expected arg 1 to be \"tabular\" in " << in);
5151                 return;
5152         }
5153
5154         // This is part of the inset proper that is usually swallowed
5155         // by Buffer::readInset
5156         lex >> token;
5157         if (!lex || token != "Tabular") {
5158                 LYXERR0("Expected arg 2 to be \"Tabular\" in " << in);
5159                 return;
5160         }
5161
5162         inset.read(lex);
5163 }
5164
5165
5166 string InsetTabular::params2string(InsetTabular const & inset)
5167 {
5168         ostringstream data;
5169         data << "tabular" << ' ';
5170         inset.write(data);
5171         data << "\\end_inset\n";
5172         return data.str();
5173 }
5174
5175
5176 } // namespace lyx