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