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