]> git.lyx.org Git - lyx.git/blob - src/insets/insettext.C
bnext-2.diff + some more boost::next stuff
[lyx.git] / src / insets / insettext.C
1 /**
2  * \file insettext.C
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Jürgen Vigna
7  *
8  * Full author contact details are available in file CREDITS
9  */
10
11 #include <config.h>
12
13 #include "insettext.h"
14
15 #include "buffer.h"
16 #include "BufferView.h"
17 #include "CutAndPaste.h"
18 #include "debug.h"
19 #include "dimension.h"
20 #include "funcrequest.h"
21 #include "gettext.h"
22 #include "intl.h"
23 #include "LaTeXFeatures.h"
24 #include "LColor.h"
25 #include "Lsstream.h"
26 #include "lyxfont.h"
27 #include "lyxcursor.h"
28 #include "lyxfind.h"
29 #include "lyxlex.h"
30 #include "lyxrow.h"
31 #include "lyxrc.h"
32 #include "lyxtext.h"
33 #include "paragraph.h"
34 #include "ParagraphParameters.h"
35 #include "trans_mgr.h"
36 #include "undo_funcs.h"
37 #include "WordLangTuple.h"
38 #include "paragraph_funcs.h"
39 #include "sgml.h"
40 #include "rowpainter.h"
41 #include "insetnewline.h"
42 #include "metricsinfo.h"
43
44 #include "frontends/Alert.h"
45 #include "frontends/Dialogs.h"
46 #include "frontends/font_metrics.h"
47 #include "frontends/LyXView.h"
48 #include "frontends/Painter.h"
49 #include "frontends/screen.h"
50
51 #include "support/textutils.h"
52 #include "support/LAssert.h"
53 #include "support/lstrings.h"
54 #include "support/lyxalgo.h" // lyx::count
55
56 #include <boost/bind.hpp>
57
58 #include <fstream>
59 #include <algorithm>
60 #include <cstdlib>
61 //#include <csignal>
62
63 using std::ostream;
64 using std::ifstream;
65 using std::endl;
66 using std::min;
67 using std::max;
68 using std::make_pair;
69 using std::vector;
70 using std::pair;
71 using std::for_each;
72
73 using lyx::pos_type;
74 using lyx::textclass_type;
75
76
77 // These functions should probably go into bufferview_funcs somehow (Jug)
78
79 void InsetText::saveLyXTextState(LyXText * t) const
80 {
81         // check if my paragraphs are still valid
82         ParagraphList::iterator it = const_cast<ParagraphList&>(paragraphs).begin();
83         ParagraphList::iterator end = const_cast<ParagraphList&>(paragraphs).end();
84         for (; it != end; ++it) {
85                 if (it == t->cursor.par())
86                         break;
87         }
88
89         if (it != end && t->cursor.pos() <= it->size()) {
90                 sstate.lpar = t->cursor.par();
91                 sstate.pos = t->cursor.pos();
92                 sstate.boundary = t->cursor.boundary();
93                 sstate.selstartpar = t->selection.start.par();
94                 sstate.selstartpos = t->selection.start.pos();
95                 sstate.selstartboundary = t->selection.start.boundary();
96                 sstate.selendpar = t->selection.end.par();
97                 sstate.selendpos = t->selection.end.pos();
98                 sstate.selendboundary = t->selection.end.boundary();
99                 sstate.selection = t->selection.set();
100                 sstate.mark_set = t->selection.mark();
101         } else {
102                 sstate.lpar = const_cast<ParagraphList&>(paragraphs).end();
103         }
104 }
105
106
107 void InsetText::restoreLyXTextState(LyXText * t) const
108 {
109         if (sstate.lpar == const_cast<ParagraphList&>(paragraphs).end())
110                 return;
111
112         t->selection.set(true);
113         /* at this point just to avoid the DEPM when setting the cursor */
114         t->selection.mark(sstate.mark_set);
115         if (sstate.selection) {
116                 t->setCursor(sstate.selstartpar, sstate.selstartpos,
117                              true, sstate.selstartboundary);
118                 t->selection.cursor = t->cursor;
119                 t->setCursor(sstate.selendpar, sstate.selendpos,
120                              true, sstate.selendboundary);
121                 t->setSelection();
122                 t->setCursor(sstate.lpar, sstate.pos);
123         } else {
124                 t->setCursor(sstate.lpar, sstate.pos, true, sstate.boundary);
125                 t->selection.cursor = t->cursor;
126                 t->selection.set(false);
127         }
128 }
129
130
131 InsetText::InnerCache::InnerCache(boost::shared_ptr<LyXText> t)
132 {
133         text = t;
134         remove = false;
135 }
136
137
138 InsetText::InsetText(BufferParams const & bp)
139         : UpdatableInset(), lt(0), in_update(false), do_resize(0),
140           do_reinit(false)
141 {
142         paragraphs.push_back(Paragraph());
143         paragraphs.begin()->layout(bp.getLyXTextClass().defaultLayout());
144         if (bp.tracking_changes)
145                 paragraphs.begin()->trackChanges();
146         init(0);
147 }
148
149
150 InsetText::InsetText(InsetText const & in)
151         : UpdatableInset(in), lt(0), in_update(false), do_resize(0),
152           do_reinit(false)
153 {
154         init(&in);
155 }
156
157
158 InsetText & InsetText::operator=(InsetText const & it)
159 {
160         init(&it);
161         return * this;
162 }
163
164
165 void InsetText::init(InsetText const * ins)
166 {
167         if (ins) {
168                 setParagraphData(ins->paragraphs);
169                 autoBreakRows = ins->autoBreakRows;
170                 drawFrame_ = ins->drawFrame_;
171                 frame_color = ins->frame_color;
172         } else {
173                 for_each(paragraphs.begin(), paragraphs.end(),
174                          boost::bind(&Paragraph::setInsetOwner, _1, this));
175
176                 the_locking_inset = 0;
177                 drawFrame_ = NEVER;
178                 frame_color = LColor::insetframe;
179                 autoBreakRows = false;
180         }
181         top_y = 0;
182         old_max_width = 0;
183         no_selection = true;
184         need_update = FULL;
185         drawTextXOffset = 0;
186         drawTextYOffset = 0;
187         locked = false;
188         old_par = paragraphs.end();
189         last_drawn_width = -1;
190         cached_bview = 0;
191         sstate.lpar = paragraphs.end();
192         in_insetAllowed = false;
193 }
194
195
196 void InsetText::clear(bool just_mark_erased)
197 {
198         if (just_mark_erased) {
199                 ParagraphList::iterator it = paragraphs.begin();
200                 ParagraphList::iterator end = paragraphs.end();
201                 for (; it != end; ++it) {
202                         it->markErased();
203                 }
204                 need_update = FULL;
205                 return;
206         }
207
208         // This is a gross hack...
209         LyXLayout_ptr old_layout = paragraphs.begin()->layout();
210
211         paragraphs.clear();
212         paragraphs.push_back(Paragraph());
213         paragraphs.begin()->setInsetOwner(this);
214         paragraphs.begin()->layout(old_layout);
215
216         reinitLyXText();
217         need_update = INIT;
218 }
219
220
221 InsetBase * InsetText::clone() const
222 {
223         return new InsetText(*this);
224 }
225
226
227 void InsetText::write(Buffer const * buf, ostream & os) const
228 {
229         os << "Text\n";
230         writeParagraphData(buf, os);
231 }
232
233
234 void InsetText::writeParagraphData(Buffer const * buf, ostream & os) const
235 {
236         ParagraphList::const_iterator it = paragraphs.begin();
237         ParagraphList::const_iterator end = paragraphs.end();
238         Paragraph::depth_type dth = 0;
239         for (; it != end; ++it) {
240                 it->write(buf, os, buf->params, dth);
241         }
242 }
243
244
245 void InsetText::read(Buffer const * buf, LyXLex & lex)
246 {
247         string token;
248         Paragraph::depth_type depth = 0;
249
250         clear(false);
251
252         if (buf->params.tracking_changes)
253                 paragraphs.begin()->trackChanges();
254
255         // delete the initial paragraph
256         paragraphs.clear();
257         ParagraphList::iterator pit = paragraphs.begin();
258
259         while (lex.isOK()) {
260                 lex.nextToken();
261                 token = lex.getString();
262                 if (token.empty())
263                         continue;
264                 if (token == "\\end_inset") {
265                         break;
266                 }
267
268                 if (token == "\\the_end") {
269                         lex.printError("\\the_end read in inset! Error in document!");
270                         return;
271                 }
272
273                 // FIXME: ugly.
274                 const_cast<Buffer*>(buf)->readParagraph(lex, token, paragraphs, pit, depth);
275         }
276
277         pit = paragraphs.begin();
278         ParagraphList::iterator const end = paragraphs.end();
279         for (; pit != end; ++pit)
280                 pit->setInsetOwner(this);
281
282         if (token != "\\end_inset") {
283                 lex.printError("Missing \\end_inset at this point. "
284                                            "Read: `$$Token'");
285         }
286         need_update = FULL;
287 }
288
289
290 void InsetText::metrics(MetricsInfo & mi, Dimension & dim) const
291 {
292         BufferView * bv = mi.base.bv;
293         LyXText * text = getLyXText(bv);
294         dim.asc = text->rows().begin()->ascent_of_text() + TEXT_TO_INSET_OFFSET;
295         dim.des = text->height - dim.asc + TEXT_TO_INSET_OFFSET;
296         dim.wid = max(textWidth(bv), int(text->width)) + 2 * TEXT_TO_INSET_OFFSET;
297         dim.wid = max(dim.wid, 10);
298         dim_ = dim;
299 }
300
301
302 int InsetText::textWidth(BufferView * bv, bool fordraw) const
303 {
304         int w = autoBreakRows ? getMaxWidth(bv, this) : -1;
305
306         if (fordraw)
307                 return max(w - 2 * TEXT_TO_INSET_OFFSET,
308                            (int)getLyXText(bv)->width);
309
310         if (w < 0)
311                 return -1;
312
313         return w - 2 * TEXT_TO_INSET_OFFSET;
314 }
315
316
317 void InsetText::draw(PainterInfo & pi, int x, int baseline) const
318 {
319         if (nodraw())
320                 return;
321
322         // update our idea of where we are. Clearly, we should
323         // not have to know this information.
324         if (top_x != x)
325                 top_x = x;
326
327         int const start_x = x;
328
329         BufferView * bv = pi.base.bv;
330         Painter & pain = pi.pain;
331
332         // repaint the background if needed
333         if (backgroundColor() != LColor::background)
334                 clearInset(bv, start_x + TEXT_TO_INSET_OFFSET, baseline);
335
336         // no draw is necessary !!!
337         if (drawFrame_ == LOCKED && !locked && paragraphs.begin()->empty()) {
338                 top_baseline = baseline;
339                 need_update = NONE;
340                 return;
341         }
342
343         if (!owner())
344                 x += scroll();
345
346         top_baseline = baseline;
347         top_y = baseline - dim_.asc;
348
349         if (last_drawn_width != dim_.wid) {
350                 need_update |= FULL;
351                 last_drawn_width = dim_.wid;
352         }
353
354         if (the_locking_inset && (cpar(bv) == inset_par)
355                 && (cpos(bv) == inset_pos)) {
356                 inset_x = cix(bv) - int(x) + drawTextXOffset;
357                 inset_y = ciy(bv) + drawTextYOffset;
358         }
359
360         bool clear = false;
361         if (!lt) {
362                 lt = getLyXText(bv);
363                 clear = true;
364         }
365         x += TEXT_TO_INSET_OFFSET;
366
367         RowList::iterator rowit = lt->rows().begin();
368         RowList::iterator end = lt->rows().end();
369
370         int y_offset = baseline - rowit->ascent_of_text();
371         int ph = pain.paperHeight();
372         int first = 0;
373         int y = y_offset;
374         while ((rowit != end) && ((y + rowit->height()) <= 0)) {
375                 y += rowit->height();
376                 first += rowit->height();
377                 ++rowit;
378         }
379         if (y_offset < 0) {
380                 lt->top_y(-y_offset);
381                 first = y;
382                 y_offset = 0;
383         } else {
384                 lt->top_y(first);
385                 first = 0;
386         }
387
388         int yf = y_offset + first;
389         y = 0;
390
391         bv->hideCursor();
392
393         while ((rowit != end) && (yf < ph)) {
394                 RowPainter rp(*bv, *lt, rowit);
395                 rp.paint(y + y_offset + first, int(x), y + lt->top_y());
396                 y += rowit->height();
397                 yf += rowit->height();
398                 ++rowit;
399         }
400
401         lt->clearPaint();
402
403         if ((drawFrame_ == ALWAYS) || (drawFrame_ == LOCKED && locked)) {
404                 drawFrame(pain, int(start_x));
405         }
406
407         x += dim_.wid - TEXT_TO_INSET_OFFSET;
408
409         if (need_update != INIT) {
410                 need_update = NONE;
411         }
412         if (clear)
413                 lt = 0;
414 }
415
416
417 void InsetText::drawFrame(Painter & pain, int x) const
418 {
419         static int const ttoD2 = TEXT_TO_INSET_OFFSET / 2;
420         frame_x = x + ttoD2;
421         frame_y = top_baseline - dim_.asc + ttoD2;
422         frame_w = dim_.wid - TEXT_TO_INSET_OFFSET;
423         frame_h = dim_.asc + dim_.des - TEXT_TO_INSET_OFFSET;
424         pain.rectangle(frame_x, frame_y, frame_w, frame_h,
425                        frame_color);
426 }
427
428
429 void InsetText::update(BufferView * bv, bool reinit)
430 {
431         if (in_update) {
432                 if (reinit && owner()) {
433                         reinitLyXText();
434                         owner()->update(bv, true);
435                 }
436                 return;
437         }
438         in_update = true;
439
440         if (reinit || need_update == INIT) {
441                 need_update = FULL;
442                 // we should put this call where we set need_update to INIT!
443                 reinitLyXText();
444                 if (owner())
445                         owner()->update(bv, true);
446                 in_update = false;
447
448                 int nw = getMaxWidth(bv, this);
449                 if (nw > 0 && old_max_width != nw) {
450                         need_update |= INIT;
451                         old_max_width = nw;
452                 }
453                 return;
454         }
455
456         if (!autoBreakRows && paragraphs.size() > 1)
457                 collapseParagraphs(bv);
458
459         if (the_locking_inset) {
460                 inset_x = cix(bv) - top_x + drawTextXOffset;
461                 inset_y = ciy(bv) + drawTextYOffset;
462                 the_locking_inset->update(bv, reinit);
463         }
464
465         bool clear = false;
466         if (!lt) {
467                 lt = getLyXText(bv);
468                 clear = true;
469         }
470         if ((need_update & CURSOR_PAR) && (lt->refreshStatus() == LyXText::REFRESH_NONE) &&
471                 the_locking_inset) {
472                 lt->updateInset(the_locking_inset);
473         }
474
475         if (lt->refreshStatus() == LyXText::REFRESH_AREA)
476                 need_update |= FULL;
477         if (clear)
478                 lt = 0;
479
480         in_update = false;
481
482         int nw = getMaxWidth(bv, this);
483         if (nw > 0 && old_max_width != nw) {
484                 need_update |= INIT;
485                 old_max_width = nw;
486         }
487 }
488
489
490 void InsetText::setUpdateStatus(BufferView * bv, int what) const
491 {
492         // this does nothing dangerous so use only a localized buffer
493         LyXText * llt = getLyXText(bv);
494
495         need_update |= what;
496         // we have to redraw us full if our LyXText REFRESH_AREA or
497         // if we don't break row so that we only have one row to update!
498         if ((llt->refreshStatus() == LyXText::REFRESH_AREA) ||
499             (!autoBreakRows &&
500              (llt->refreshStatus() == LyXText::REFRESH_ROW)))
501         {
502                 need_update |= FULL;
503         } else if (llt->refreshStatus() == LyXText::REFRESH_ROW) {
504                 need_update |= CURSOR_PAR;
505         }
506
507         // this to not draw a selection when we redraw all of it!
508         if (need_update & CURSOR && !(need_update & SELECTION)) {
509                 if (llt->selection.set())
510                         need_update = FULL;
511                 llt->clearSelection();
512         }
513 }
514
515
516 void InsetText::updateLocal(BufferView * bv, int what, bool mark_dirty)
517 {
518         if (!autoBreakRows && paragraphs.size() > 1)
519                 collapseParagraphs(bv);
520
521         bool clear = false;
522         if (!lt) {
523                 lt = getLyXText(bv);
524                 clear = true;
525         }
526         lt->fullRebreak();
527         setUpdateStatus(bv, what);
528         bool flag = mark_dirty ||
529                 (((need_update != CURSOR) && (need_update != NONE)) ||
530                  (lt->refreshStatus() != LyXText::REFRESH_NONE) || lt->selection.set());
531         if (!lt->selection.set())
532                 lt->selection.cursor = lt->cursor;
533
534         bv->fitCursor();
535
536         if (flag) {
537                 lt->postPaint(0);
538                 bv->updateInset(const_cast<InsetText *>(this));
539         }
540
541         if (clear)
542                 lt = 0;
543
544         if (need_update == CURSOR)
545                 need_update = NONE;
546         bv->owner()->view_state_changed();
547         bv->owner()->updateMenubar();
548         bv->owner()->updateToolbar();
549         if (old_par != cpar(bv)) {
550                 bv->owner()->setLayout(cpar(bv)->layout()->name());
551                 old_par = cpar(bv);
552         }
553 }
554
555
556 string const InsetText::editMessage() const
557 {
558         return _("Opened Text Inset");
559 }
560
561
562 void InsetText::insetUnlock(BufferView * bv)
563 {
564         if (the_locking_inset) {
565                 the_locking_inset->insetUnlock(bv);
566                 the_locking_inset = 0;
567                 updateLocal(bv, CURSOR_PAR, false);
568         }
569         no_selection = true;
570         locked = false;
571         int code = NONE;
572         bool clear = false;
573
574         if (!lt) {
575                 lt = getLyXText(bv);
576                 clear = true;
577         }
578         if (lt->selection.set()) {
579                 lt->clearSelection();
580                 code = FULL;
581         } else if (owner()) {
582                 bv->owner()->setLayout(owner()->getLyXText(bv)
583                                        ->cursor.par()->layout()->name());
584         } else
585                 bv->owner()->setLayout(bv->text->cursor.par()->layout()->name());
586         // hack for deleteEmptyParMech
587         ParagraphList::iterator first_par = paragraphs.begin();
588         if (!first_par->empty()) {
589                 lt->setCursor(first_par, 0);
590         } else if (paragraphs.size() > 1) {
591                 lt->setCursor(boost::next(first_par), 0);
592         }
593         if (clear)
594                 lt = 0;
595 #if 0
596         updateLocal(bv, code, false);
597 #else
598         if (code != NONE)
599                 setUpdateStatus(bv, code);
600 #endif
601 }
602
603
604 void InsetText::lockInset(BufferView * bv)
605 {
606         locked = true;
607         the_locking_inset = 0;
608         inset_pos = inset_x = inset_y = 0;
609         inset_boundary = false;
610         inset_par = paragraphs.end();
611         old_par = paragraphs.end();
612         bool clear = false;
613         if (!lt) {
614                 lt = getLyXText(bv);
615                 clear = true;
616         }
617         lt->setCursor(paragraphs.begin(), 0);
618         lt->clearSelection();
619         finishUndo();
620         // If the inset is empty set the language of the current font to the
621         // language to the surronding text (if different).
622         if (paragraphs.begin()->empty() && paragraphs.size() == 1 &&
623                 bv->getParentLanguage(this) != lt->current_font.language()) {
624                 LyXFont font(LyXFont::ALL_IGNORE);
625                 font.setLanguage(bv->getParentLanguage(this));
626                 setFont(bv, font, false);
627         }
628         if (clear)
629                 lt = 0;
630         int code = CURSOR;
631         if (drawFrame_ == LOCKED)
632                 code = CURSOR|DRAW_FRAME;
633         setUpdateStatus(bv, code);
634 }
635
636
637 void InsetText::lockInset(BufferView * bv, UpdatableInset * inset)
638 {
639         the_locking_inset = inset;
640         inset_x = cix(bv) - top_x + drawTextXOffset;
641         inset_y = ciy(bv) + drawTextYOffset;
642         inset_pos = cpos(bv);
643         inset_par = cpar(bv);
644         inset_boundary = cboundary(bv);
645         updateLocal(bv, CURSOR, false);
646 }
647
648
649 bool InsetText::lockInsetInInset(BufferView * bv, UpdatableInset * inset)
650 {
651         lyxerr[Debug::INSETS] << "InsetText::LockInsetInInset("
652                               << inset << "): ";
653         if (!inset)
654                 return false;
655         if (!the_locking_inset) {
656                 ParagraphList::iterator pit = paragraphs.begin();
657                 ParagraphList::iterator pend = paragraphs.end();
658
659                 int const id = inset->id();
660                 for (; pit != pend; ++pit) {
661                         InsetList::iterator it =
662                                 pit->insetlist.begin();
663                         InsetList::iterator const end =
664                                 pit->insetlist.end();
665                         for (; it != end; ++it) {
666                                 if (it->inset == inset) {
667                                         getLyXText(bv)->setCursorIntern(pit, it->pos);
668                                         lockInset(bv, inset);
669                                         return true;
670                                 }
671                                 if (it->inset->getInsetFromID(id)) {
672                                         getLyXText(bv)->setCursorIntern(pit, it->pos);
673                                         it->inset->localDispatch(FuncRequest(bv, LFUN_INSET_EDIT));
674                                         return the_locking_inset->lockInsetInInset(bv, inset);
675                                 }
676                         }
677                 }
678                 return false;
679         }
680         if (inset == cpar(bv)->getInset(cpos(bv))) {
681                 lyxerr[Debug::INSETS] << "OK" << endl;
682                 lockInset(bv, inset);
683                 return true;
684         } else if (the_locking_inset && (the_locking_inset == inset)) {
685                 if (cpar(bv) == inset_par && cpos(bv) == inset_pos) {
686                         lyxerr[Debug::INSETS] << "OK" << endl;
687                         inset_x = cix(bv) - top_x + drawTextXOffset;
688                         inset_y = ciy(bv) + drawTextYOffset;
689                 } else {
690                         lyxerr[Debug::INSETS] << "cursor.pos != inset_pos" << endl;
691                 }
692         } else if (the_locking_inset) {
693                 lyxerr[Debug::INSETS] << "MAYBE" << endl;
694                 return the_locking_inset->lockInsetInInset(bv, inset);
695         }
696         lyxerr[Debug::INSETS] << "NOT OK" << endl;
697         return false;
698 }
699
700
701 bool InsetText::unlockInsetInInset(BufferView * bv, UpdatableInset * inset,
702                                    bool lr)
703 {
704         if (!the_locking_inset)
705                 return false;
706         if (the_locking_inset == inset) {
707                 the_locking_inset->insetUnlock(bv);
708                 getLyXText(bv)->updateInset(inset);
709                 the_locking_inset = 0;
710                 if (lr)
711                         moveRightIntern(bv, true, false);
712                 old_par = paragraphs.end(); // force layout setting
713                 if (scroll())
714                         scroll(bv, 0.0F);
715                 else
716                         updateLocal(bv, CURSOR, false);
717                 return true;
718         }
719         return the_locking_inset->unlockInsetInInset(bv, inset, lr);
720 }
721
722
723 bool InsetText::updateInsetInInset(BufferView * bv, Inset * inset)
724 {
725         if (!autoBreakRows && paragraphs.size() > 1)
726                 collapseParagraphs(bv);
727
728         if (inset == this)
729                 return true;
730
731         bool clear = false;
732         if (!lt) {
733                 lt = getLyXText(bv);
734                 clear = true;
735         }
736         if (inset->owner() != this) {
737                 int ustat = CURSOR_PAR;
738                 bool found = false;
739                 UpdatableInset * tl_inset = the_locking_inset;
740                 if (tl_inset)
741                         found = tl_inset->updateInsetInInset(bv, inset);
742                 if (!found) {
743                         tl_inset = static_cast<UpdatableInset *>(inset);
744                         while(tl_inset->owner() && tl_inset->owner() != this)
745                                 tl_inset = static_cast<UpdatableInset *>(tl_inset->owner());
746                         if (!tl_inset->owner())
747                                 return false;
748                         found = tl_inset->updateInsetInInset(bv, inset);
749                         ustat = FULL;
750                 }
751                 if (found)
752                         lt->updateInset(tl_inset);
753                 if (clear)
754                         lt = 0;
755                 if (found)
756                         setUpdateStatus(bv, ustat);
757                 return found;
758         }
759         bool found = lt->updateInset(inset);
760         if (clear)
761                 lt = 0;
762         if (found) {
763                 setUpdateStatus(bv, CURSOR_PAR);
764                 if (the_locking_inset &&
765                     cpar(bv) == inset_par && cpos(bv) == inset_pos)
766                 {
767                         inset_x = cix(bv) - top_x + drawTextXOffset;
768                         inset_y = ciy(bv) + drawTextYOffset;
769                 }
770         }
771         return found;
772 }
773
774
775 void InsetText::lfunMousePress(FuncRequest const & cmd)
776 {
777         no_selection = true;
778
779         // use this to check mouse motion for selection!
780         mouse_x = cmd.x;
781         mouse_y = cmd.y;
782
783         BufferView * bv = cmd.view();
784         FuncRequest cmd1 = cmd;
785         cmd1.x -= inset_x;
786         cmd1.y -= inset_y;
787         if (!locked)
788                 lockInset(bv);
789
790         int tmp_x = cmd.x - drawTextXOffset;
791         int tmp_y = cmd.y + dim_.asc - getLyXText(bv)->top_y();
792         Inset * inset = getLyXText(bv)->checkInsetHit(tmp_x, tmp_y);
793
794         if (the_locking_inset) {
795                 if (the_locking_inset == inset) {
796                         the_locking_inset->localDispatch(cmd1);
797                         return;
798                 }
799                 // otherwise only unlock the_locking_inset
800                 the_locking_inset->insetUnlock(bv);
801                 the_locking_inset = 0;
802         }
803         if (!inset)
804                 no_selection = false;
805
806         if (bv->theLockingInset()) {
807                 if (isHighlyEditableInset(inset)) {
808                         // We just have to lock the inset before calling a
809                         // PressEvent on it!
810                         UpdatableInset * uinset = static_cast<UpdatableInset*>(inset);
811                         if (!bv->lockInset(uinset)) {
812                                 lyxerr[Debug::INSETS] << "Cannot lock inset" << endl;
813                         }
814                         inset->localDispatch(cmd1);
815                         if (the_locking_inset)
816                                 updateLocal(bv, CURSOR, false);
817                         return;
818                 }
819         }
820         if (!inset) {
821                 bool paste_internally = false;
822                 if (cmd.button() == mouse_button::button2 && getLyXText(bv)->selection.set()) {
823                         localDispatch(FuncRequest(bv, LFUN_COPY));
824                         paste_internally = true;
825                 }
826                 bool clear = false;
827                 if (!lt) {
828                         lt = getLyXText(bv);
829                         clear = true;
830                 }
831                 int old_top_y = lt->top_y();
832
833                 lt->setCursorFromCoordinates(cmd.x - drawTextXOffset,
834                                              cmd.y + dim_.asc);
835                 // set the selection cursor!
836                 lt->selection.cursor = lt->cursor;
837                 lt->cursor.x_fix(lt->cursor.x());
838
839                 if (lt->selection.set()) {
840                         lt->clearSelection();
841                         updateLocal(bv, FULL, false);
842                 } else {
843                         lt->clearSelection();
844                         updateLocal(bv, CURSOR, false);
845                 }
846
847                 if (clear)
848                         lt = 0;
849
850                 bv->owner()->setLayout(cpar(bv)->layout()->name());
851
852                 // we moved the view we cannot do mouse selection in this case!
853                 if (getLyXText(bv)->top_y() != old_top_y)
854                         no_selection = true;
855                 old_par = cpar(bv);
856                 // Insert primary selection with middle mouse
857                 // if there is a local selection in the current buffer,
858                 // insert this
859                 if (cmd.button() == mouse_button::button2) {
860                         if (paste_internally)
861                                 localDispatch(FuncRequest(bv, LFUN_PASTE));
862                         else
863                                 localDispatch(FuncRequest(bv, LFUN_PASTESELECTION, "paragraph"));
864                 }
865         } else {
866                 getLyXText(bv)->clearSelection();
867         }
868 }
869
870
871 bool InsetText::lfunMouseRelease(FuncRequest const & cmd)
872 {
873         BufferView * bv = cmd.view();
874         FuncRequest cmd1 = cmd;
875         cmd1.x -= inset_x;
876         cmd1.y -= inset_y;
877
878         no_selection = true;
879         if (the_locking_inset)
880                 return the_locking_inset->localDispatch(cmd1);
881
882         int tmp_x = cmd.x - drawTextXOffset;
883         int tmp_y = cmd.y + dim_.asc - getLyXText(bv)->top_y();
884         Inset * inset = getLyXText(bv)->checkInsetHit(tmp_x, tmp_y);
885         bool ret = false;
886         if (inset) {
887 // This code should probably be removed now. Simple insets
888 // (!highlyEditable) can actually take the localDispatch,
889 // and turn it into edit() if necessary. But we still
890 // need to deal properly with the whole relative vs.
891 // absolute mouse co-ords thing in a realiable, sensible way
892 #if 0
893                 if (isHighlyEditableInset(inset))
894                         ret = inset->localDispatch(cmd1);
895                 else {
896                         inset_x = cix(bv) - top_x + drawTextXOffset;
897                         inset_y = ciy(bv) + drawTextYOffset;
898                         cmd1.x = cmd.x - inset_x;
899                         cmd1.y = cmd.x - inset_y;
900                         inset->edit(bv, cmd1.x, cmd1.y, cmd.button());
901                         ret = true;
902                 }
903 #endif
904                 ret = inset->localDispatch(cmd1);
905                 updateLocal(bv, CURSOR_PAR, false);
906
907         }
908         return ret;
909 }
910
911
912 void InsetText::lfunMouseMotion(FuncRequest const & cmd)
913 {
914         FuncRequest cmd1 = cmd;
915         cmd1.x -= inset_x;
916         cmd1.y -= inset_y;
917
918         if (the_locking_inset) {
919                 the_locking_inset->localDispatch(cmd1);
920                 return;
921         }
922
923         if (no_selection || (mouse_x == cmd.x && mouse_y == cmd.y))
924                 return;
925
926         BufferView * bv = cmd.view();
927         bool clear = false;
928         if (!lt) {
929                 lt = getLyXText(bv);
930                 clear = true;
931         }
932         LyXCursor cur = lt->cursor;
933         lt->setCursorFromCoordinates
934                 (cmd.x - drawTextXOffset, cmd.y + dim_.asc);
935         lt->cursor.x_fix(lt->cursor.x());
936         if (cur == lt->cursor) {
937                 if (clear)
938                         lt = 0;
939                 return;
940         }
941         lt->setSelection();
942         bool flag = (lt->toggle_cursor.par() != lt->toggle_end_cursor.par() ||
943                                  lt->toggle_cursor.pos() != lt->toggle_end_cursor.pos());
944         if (clear)
945                 lt = 0;
946         if (flag) {
947                 updateLocal(bv, SELECTION, false);
948         }
949 }
950
951
952 Inset::RESULT InsetText::localDispatch(FuncRequest const & cmd)
953 {
954         BufferView * bv = cmd.view();
955
956         if (cmd.action == LFUN_INSET_EDIT) {
957                 UpdatableInset::localDispatch(cmd);
958
959                 if (!bv->lockInset(this)) {
960                         lyxerr[Debug::INSETS] << "Cannot lock inset" << endl;
961                         return DISPATCHED;
962                 }
963
964                 locked = true;
965                 the_locking_inset = 0;
966                 inset_pos = inset_x = inset_y = 0;
967                 inset_boundary = false;
968                 inset_par = paragraphs.end();
969                 old_par = paragraphs.end();
970
971                 bool clear = false;
972                 if (!lt) {
973                         lt = getLyXText(bv);
974                         clear = true;
975                 }
976
977                 if (cmd.argument.size()) {
978                         if (cmd.argument == "left")
979                                 lt->setCursor(paragraphs.begin(), 0);
980                         else {
981                                 ParagraphList::iterator it = paragraphs.begin();
982                                 ParagraphList::iterator end = paragraphs.end();
983                                 while (boost::next(it) != end)
984                                         ++it;
985                 //              int const pos = (p->size() ? p->size()-1 : p->size());
986                                 lt->setCursor(it, it->size());
987                         }
988                 } else {
989                         int tmp_y = (cmd.y < 0) ? 0 : cmd.y;
990                         // we put here -1 and not button as now the button in the
991                         // edit call should not be needed we will fix this in 1.3.x
992                         // cycle hopefully (Jug 20020509)
993                         // FIXME: GUII I've changed this to none: probably WRONG
994                         if (!checkAndActivateInset(bv, cmd.x, tmp_y, mouse_button::none)) {
995                                 lt->setCursorFromCoordinates(cmd.x - drawTextXOffset,
996                                                                         cmd.y + dim_.asc);
997                                 lt->cursor.x_fix(lt->cursor.x());
998                         }
999                 }
1000
1001                 lt->clearSelection();
1002                 finishUndo();
1003
1004                 // If the inset is empty set the language of the current font to the
1005                 // language to the surronding text (if different).
1006                 if (paragraphs.begin()->empty() &&
1007                     paragraphs.size() == 1 &&
1008                     bv->getParentLanguage(this) != lt->current_font.language())
1009                 {
1010                         LyXFont font(LyXFont::ALL_IGNORE);
1011                         font.setLanguage(bv->getParentLanguage(this));
1012                         setFont(bv, font, false);
1013                 }
1014
1015                 if (clear)
1016                         lt = 0;
1017                 int code = CURSOR;
1018                 if (drawFrame_ == LOCKED)
1019                         code = CURSOR | DRAW_FRAME;
1020
1021                 updateLocal(bv, code, false);
1022                 // Tell the paragraph dialog that we've entered an insettext.
1023                 bv->dispatch(FuncRequest(LFUN_PARAGRAPH_UPDATE));
1024                 return DISPATCHED;
1025         }
1026
1027
1028         switch (cmd.action) {
1029                 case LFUN_MOUSE_PRESS:
1030                         lfunMousePress(cmd);
1031                         return DISPATCHED;
1032                 case LFUN_MOUSE_MOTION:
1033                         lfunMouseMotion(cmd);
1034                         return DISPATCHED;
1035                 case LFUN_MOUSE_RELEASE:
1036                         return lfunMouseRelease(cmd) ? DISPATCHED : UNDISPATCHED;
1037                 default:
1038                         break;
1039         }
1040
1041         bool was_empty = (paragraphs.begin()->empty() &&
1042                           paragraphs.size() == 1);
1043
1044         no_selection = false;
1045         RESULT result = UpdatableInset::localDispatch(cmd);
1046         if (result != UNDISPATCHED)
1047                 return DISPATCHED;
1048
1049         result = DISPATCHED;
1050         if (cmd.action < 0 && cmd.argument.empty())
1051                 return FINISHED;
1052
1053         if (the_locking_inset) {
1054                 result = the_locking_inset->localDispatch(cmd);
1055                 if (result == DISPATCHED_NOUPDATE)
1056                         return result;
1057                 else if (result == DISPATCHED) {
1058                         updateLocal(bv, CURSOR_PAR, false);
1059                         return result;
1060                 } else if (result >= FINISHED) {
1061                         switch (result) {
1062                         case FINISHED_RIGHT:
1063                                 moveRightIntern(bv, false, false);
1064                                 result = DISPATCHED;
1065                                 break;
1066                         case FINISHED_UP:
1067                                 if ((result = moveUp(bv)) >= FINISHED) {
1068                                         updateLocal(bv, CURSOR, false);
1069                                         bv->unlockInset(this);
1070                                 }
1071                                 break;
1072                         case FINISHED_DOWN:
1073                                 if ((result = moveDown(bv)) >= FINISHED) {
1074                                         updateLocal(bv, CURSOR, false);
1075                                         bv->unlockInset(this);
1076                                 }
1077                                 break;
1078                         default:
1079                                 result = DISPATCHED;
1080                                 break;
1081                         }
1082                         the_locking_inset = 0;
1083                         updateLocal(bv, CURSOR, false);
1084                         // make sure status gets reset immediately
1085                         bv->owner()->clearMessage();
1086                         return result;
1087                 }
1088         }
1089         bool clear = false;
1090         if (!lt) {
1091                 lt = getLyXText(bv);
1092                 clear = true;
1093         }
1094         int updwhat = 0;
1095         int updflag = false;
1096
1097         // what type of update to do on a cursor movement
1098         int cursor_update = CURSOR;
1099
1100         if (lt->selection.set())
1101                 cursor_update = SELECTION;
1102
1103         switch (cmd.action) {
1104
1105         // Normal chars
1106         case LFUN_SELFINSERT:
1107                 if (bv->buffer()->isReadonly()) {
1108 //          setErrorMessage(N_("Document is read only"));
1109                         break;
1110                 }
1111                 if (!cmd.argument.empty()) {
1112                         /* Automatically delete the currently selected
1113                          * text and replace it with what is being
1114                          * typed in now. Depends on lyxrc settings
1115                          * "auto_region_delete", which defaults to
1116                          * true (on). */
1117 #if 0
1118                         // This should not be needed here and is also WRONG!
1119                         setUndo(bv, Undo::INSERT, lt->cursor.par());
1120 #endif
1121                         bv->switchKeyMap();
1122                         if (lyxrc.auto_region_delete) {
1123                                 if (lt->selection.set()) {
1124                                         lt->cutSelection(false, false);
1125                                 }
1126                         }
1127                         lt->clearSelection();
1128                         for (string::size_type i = 0; i < cmd.argument.length(); ++i) {
1129                                 bv->owner()->getIntl().getTransManager().
1130                                         TranslateAndInsert(cmd.argument[i], lt);
1131                         }
1132                 }
1133                 lt->selection.cursor = lt->cursor;
1134                 updwhat = CURSOR | CURSOR_PAR;
1135                 updflag = true;
1136                 result = DISPATCHED_NOUPDATE;
1137                 break;
1138
1139         // cursor movements that need special handling
1140
1141         case LFUN_RIGHT:
1142                 result = moveRight(bv);
1143                 finishUndo();
1144                 updwhat = cursor_update;
1145                 break;
1146         case LFUN_LEFT:
1147                 finishUndo();
1148                 result = moveLeft(bv);
1149                 updwhat = cursor_update;
1150                 break;
1151         case LFUN_DOWN:
1152                 finishUndo();
1153                 result = moveDown(bv);
1154                 updwhat = cursor_update;
1155                 break;
1156         case LFUN_UP:
1157                 finishUndo();
1158                 result = moveUp(bv);
1159                 updwhat = cursor_update;
1160                 break;
1161
1162         case LFUN_PRIOR:
1163                 if (crow(bv) == lt->rows().begin())
1164                         result = FINISHED_UP;
1165                 else {
1166                         lt->cursorPrevious();
1167                         lt->clearSelection();
1168                         result = DISPATCHED_NOUPDATE;
1169                 }
1170                 updwhat = cursor_update;
1171                 break;
1172
1173         case LFUN_NEXT:
1174                 if (boost::next(crow(bv)) == lt->rows().end())
1175                         result = FINISHED_DOWN;
1176                 else {
1177                         lt->cursorNext();
1178                         lt->clearSelection();
1179                         result = DISPATCHED_NOUPDATE;
1180                 }
1181                 updwhat = cursor_update;
1182                 break;
1183
1184         case LFUN_BACKSPACE: {
1185                 if (lt->selection.set())
1186                         lt->cutSelection(true, false);
1187                 else
1188                         lt->backspace();
1189                 updwhat = CURSOR_PAR;
1190                 updflag = true;
1191                 break;
1192         }
1193
1194         case LFUN_DELETE: {
1195                 if (lt->selection.set()) {
1196                         lt->cutSelection(true, false);
1197                 } else {
1198                         lt->Delete();
1199                 }
1200                 updwhat = CURSOR_PAR;
1201                 updflag = true;
1202                 break;
1203         }
1204
1205         case LFUN_CUT: {
1206                 lt->cutSelection(true, true);
1207                 updwhat = CURSOR_PAR;
1208                 updflag = true;
1209                 break;
1210         }
1211
1212         case LFUN_COPY:
1213                 finishUndo();
1214                 lt->copySelection();
1215                 updwhat = CURSOR_PAR;
1216                 break;
1217
1218         case LFUN_PASTESELECTION:
1219         {
1220                 string const clip(bv->getClipboard());
1221
1222                 if (clip.empty())
1223                         break;
1224                 if (cmd.argument == "paragraph") {
1225                         lt->insertStringAsParagraphs(clip);
1226                 } else {
1227                         lt->insertStringAsLines(clip);
1228                 }
1229                 // bug 393
1230                 lt->clearSelection();
1231
1232                 updwhat = CURSOR_PAR;
1233                 updflag = true;
1234                 break;
1235         }
1236
1237         case LFUN_PASTE: {
1238                 if (!autoBreakRows) {
1239                         if (CutAndPaste::nrOfParagraphs() > 1) {
1240 #ifdef WITH_WARNINGS
1241 #warning FIXME horrendously bad UI
1242 #endif
1243                                 Alert::error(_("Paste failed"), _("Cannot include more than one paragraph."));
1244                                 break;
1245                         }
1246                 }
1247
1248                 size_t sel_index = 0;
1249                 string const & arg = cmd.argument;
1250                 if (isStrUnsignedInt(arg)) {
1251                         size_t const paste_arg = strToUnsignedInt(arg);
1252 #warning FIXME Check if the arg is in the domain of available selections.
1253                         sel_index = paste_arg;
1254                 }
1255                 lt->pasteSelection(sel_index);
1256                 // bug 393
1257                 lt->clearSelection();
1258                 updwhat = CURSOR_PAR;
1259                 updflag = true;
1260                 break;
1261         }
1262
1263         case LFUN_BREAKPARAGRAPH:
1264                 if (!autoBreakRows) {
1265                         result = DISPATCHED;
1266                         break;
1267                 }
1268                 lt->breakParagraph(paragraphs, 0);
1269                 updwhat = CURSOR | FULL;
1270                 updflag = true;
1271                 break;
1272
1273         case LFUN_BREAKPARAGRAPHKEEPLAYOUT:
1274                 if (!autoBreakRows) {
1275                         result = DISPATCHED;
1276                         break;
1277                 }
1278                 lt->breakParagraph(paragraphs, 1);
1279                 updwhat = CURSOR | FULL;
1280                 updflag = true;
1281                 break;
1282
1283         case LFUN_BREAKLINE: {
1284                 if (!autoBreakRows) {
1285                         result = DISPATCHED;
1286                         break;
1287                 }
1288
1289                 lt->insertInset(new InsetNewline);
1290                 updwhat = CURSOR | CURSOR_PAR;
1291                 updflag = true;
1292                 break;
1293         }
1294
1295         case LFUN_LAYOUT:
1296                 // do not set layouts on non breakable textinsets
1297                 if (autoBreakRows) {
1298                         string cur_layout = cpar(bv)->layout()->name();
1299
1300                         // Derive layout number from given argument (string)
1301                         // and current buffer's textclass (number). */
1302                         LyXTextClass const & tclass =
1303                                 bv->buffer()->params.getLyXTextClass();
1304                         string layout = cmd.argument;
1305                         bool hasLayout = tclass.hasLayout(layout);
1306
1307                         // If the entry is obsolete, use the new one instead.
1308                         if (hasLayout) {
1309                                 string const & obs =
1310                                         tclass[layout]->obsoleted_by();
1311                                 if (!obs.empty())
1312                                         layout = obs;
1313                         }
1314
1315                         // see if we found the layout number:
1316                         if (!hasLayout) {
1317                                 FuncRequest lf(LFUN_MESSAGE, N_("Layout ") + cmd.argument + N_(" not known"));
1318                                 bv->owner()->dispatch(lf);
1319                                 break;
1320                         }
1321
1322                         if (cur_layout != layout) {
1323                                 cur_layout = layout;
1324                                 lt->setLayout(layout);
1325                                 bv->owner()->setLayout(cpar(bv)->layout()->name());
1326                                 updwhat = CURSOR_PAR;
1327                                 updflag = true;
1328                         }
1329                 } else {
1330                         // reset the layout box
1331                         bv->owner()->setLayout(cpar(bv)->layout()->name());
1332                 }
1333                 break;
1334         case LFUN_PARAGRAPH_SPACING:
1335                 // This one is absolutely not working. When fiddling with this
1336                 // it also seems to me that the paragraphs inside the insettext
1337                 // inherit bufferparams/paragraphparams in a strange way. (Lgb)
1338                 // FIXME: how old is this comment ? ...
1339         {
1340                 ParagraphList::iterator pit = lt->cursor.par();
1341                 Spacing::Space cur_spacing = pit->params().spacing().getSpace();
1342                 float cur_value = 1.0;
1343                 if (cur_spacing == Spacing::Other) {
1344                         cur_value = pit->params().spacing().getValue();
1345                 }
1346
1347                 istringstream istr(STRCONV(cmd.argument));
1348                 string tmp;
1349                 istr >> tmp;
1350                 Spacing::Space new_spacing = cur_spacing;
1351                 float new_value = cur_value;
1352                 if (tmp.empty()) {
1353                         lyxerr << "Missing argument to `paragraph-spacing'"
1354                                    << endl;
1355                 } else if (tmp == "single") {
1356                         new_spacing = Spacing::Single;
1357                 } else if (tmp == "onehalf") {
1358                         new_spacing = Spacing::Onehalf;
1359                 } else if (tmp == "double") {
1360                         new_spacing = Spacing::Double;
1361                 } else if (tmp == "other") {
1362                         new_spacing = Spacing::Other;
1363                         float tmpval = 0.0;
1364                         istr >> tmpval;
1365                         lyxerr << "new_value = " << tmpval << endl;
1366                         if (tmpval != 0.0)
1367                                 new_value = tmpval;
1368                 } else if (tmp == "default") {
1369                         new_spacing = Spacing::Default;
1370                 } else {
1371                         lyxerr << _("Unknown spacing argument: ")
1372                                    << cmd.argument << endl;
1373                 }
1374                 if (cur_spacing != new_spacing || cur_value != new_value) {
1375                         pit->params().spacing(Spacing(new_spacing, new_value));
1376                         updwhat = CURSOR_PAR;
1377                         updflag = true;
1378                 }
1379         }
1380         break;
1381
1382         // These need to do repaints but don't require
1383         // special handling otherwise. A *lot* of the
1384         // above could probably be done similarly ...
1385
1386         case LFUN_HOME:
1387         case LFUN_END:
1388         case LFUN_WORDLEFT:
1389         case LFUN_WORDRIGHT:
1390         // these two are really unhandled ...
1391         case LFUN_ENDBUF:
1392         case LFUN_BEGINNINGBUF:
1393                 updwhat = cursor_update;
1394                 if (!bv->dispatch(cmd))
1395                         result = UNDISPATCHED;
1396                 break;
1397
1398         case LFUN_RIGHTSEL:
1399         case LFUN_UPSEL:
1400         case LFUN_DOWNSEL:
1401         case LFUN_LEFTSEL:
1402         case LFUN_HOMESEL:
1403         case LFUN_ENDSEL:
1404         case LFUN_WORDLEFTSEL:
1405         case LFUN_WORDRIGHTSEL:
1406                 updwhat = SELECTION;
1407
1408                 // fallthrough
1409
1410         default:
1411                 if (!bv->dispatch(cmd))
1412                         result = UNDISPATCHED;
1413                 break;
1414         }
1415
1416         if (clear)
1417                 lt = 0;
1418         if (updwhat > 0)
1419                 updateLocal(bv, updwhat, updflag);
1420         /// If the action has deleted all text in the inset, we need to change the
1421         // language to the language of the surronding text.
1422         if (!was_empty && paragraphs.begin()->empty() &&
1423             paragraphs.size() == 1) {
1424                 LyXFont font(LyXFont::ALL_IGNORE);
1425                 font.setLanguage(bv->getParentLanguage(this));
1426                 setFont(bv, font, false);
1427         }
1428
1429         if (result >= FINISHED)
1430                 bv->unlockInset(this);
1431
1432         if (result == DISPATCHED_NOUPDATE && (need_update & FULL))
1433                 result = DISPATCHED;
1434         return result;
1435 }
1436
1437
1438 int InsetText::latex(Buffer const * buf, ostream & os,
1439                      LatexRunParams const & runparams) const
1440 {
1441         TexRow texrow;
1442         latexParagraphs(buf, paragraphs, os, texrow, runparams);
1443         return texrow.rows();
1444 }
1445
1446
1447 int InsetText::ascii(Buffer const * buf, ostream & os, int linelen) const
1448 {
1449         unsigned int lines = 0;
1450
1451         ParagraphList::const_iterator beg = paragraphs.begin();
1452         ParagraphList::const_iterator end = paragraphs.end();
1453         ParagraphList::const_iterator it = beg;
1454         for (; it != end; ++it) {
1455                 string const tmp = buf->asciiParagraph(*it, linelen, it == beg);
1456                 lines += lyx::count(tmp.begin(), tmp.end(), '\n');
1457                 os << tmp;
1458         }
1459         return lines;
1460 }
1461
1462
1463 int InsetText::docbook(Buffer const * buf, ostream & os, bool mixcont) const
1464 {
1465         unsigned int lines = 0;
1466
1467         vector<string> environment_stack(10);
1468         vector<string> environment_inner(10);
1469
1470         int const command_depth = 0;
1471         string item_name;
1472
1473         Paragraph::depth_type depth = 0; // paragraph depth
1474
1475         ParagraphList::iterator pit = const_cast<ParagraphList&>(paragraphs).begin();
1476         ParagraphList::iterator pend = const_cast<ParagraphList&>(paragraphs).end();
1477
1478         for (; pit != pend; ++pit) {
1479                 string sgmlparam;
1480                 int desc_on = 0; // description mode
1481
1482                 LyXLayout_ptr const & style = pit->layout();
1483
1484                 // environment tag closing
1485                 for (; depth > pit->params().depth(); --depth) {
1486                         if (environment_inner[depth] != "!-- --") {
1487                                 item_name = "listitem";
1488                                 lines += sgml::closeTag(os, command_depth + depth, mixcont, item_name);
1489                                 if (environment_inner[depth] == "varlistentry")
1490                                         lines += sgml::closeTag(os, depth+command_depth, mixcont, environment_inner[depth]);
1491                         }
1492                         lines += sgml::closeTag(os, depth + command_depth, mixcont, environment_stack[depth]);
1493                         environment_stack[depth].erase();
1494                         environment_inner[depth].erase();
1495                 }
1496
1497                 if (depth == pit->params().depth()
1498                    && environment_stack[depth] != style->latexname()
1499                    && !environment_stack[depth].empty()) {
1500                         if (environment_inner[depth] != "!-- --") {
1501                                 item_name= "listitem";
1502                                 lines += sgml::closeTag(os, command_depth+depth, mixcont, item_name);
1503                                 if (environment_inner[depth] == "varlistentry")
1504                                         lines += sgml::closeTag(os, depth + command_depth, mixcont, environment_inner[depth]);
1505                         }
1506
1507                         lines += sgml::closeTag(os, depth + command_depth, mixcont, environment_stack[depth]);
1508
1509                         environment_stack[depth].erase();
1510                         environment_inner[depth].erase();
1511                 }
1512
1513                 // Write opening SGML tags.
1514                 switch (style->latextype) {
1515                 case LATEX_PARAGRAPH:
1516                         lines += sgml::openTag(os, depth + command_depth, mixcont, style->latexname());
1517                         break;
1518
1519                 case LATEX_COMMAND:
1520                         buf->sgmlError(pit, 0,  _("Error: LatexType Command not allowed here.\n"));
1521                         return -1;
1522                         break;
1523
1524                 case LATEX_ENVIRONMENT:
1525                 case LATEX_ITEM_ENVIRONMENT:
1526                         if (depth < pit->params().depth()) {
1527                                 depth = pit->params().depth();
1528                                 environment_stack[depth].erase();
1529                         }
1530
1531                         if (environment_stack[depth] != style->latexname()) {
1532                                 if (environment_stack.size() == depth + 1) {
1533                                         environment_stack.push_back("!-- --");
1534                                         environment_inner.push_back("!-- --");
1535                                 }
1536                                 environment_stack[depth] = style->latexname();
1537                                 environment_inner[depth] = "!-- --";
1538                                 lines += sgml::openTag(os, depth + command_depth, mixcont, environment_stack[depth]);
1539                         } else {
1540                                 if (environment_inner[depth] != "!-- --") {
1541                                         item_name= "listitem";
1542                                         lines += sgml::closeTag(os, command_depth + depth, mixcont, item_name);
1543                                         if (environment_inner[depth] == "varlistentry")
1544                                                 lines += sgml::closeTag(os, depth + command_depth, mixcont, environment_inner[depth]);
1545                                 }
1546                         }
1547
1548                         if (style->latextype == LATEX_ENVIRONMENT) {
1549                                 if (!style->latexparam().empty()) {
1550                                         if (style->latexparam() == "CDATA")
1551                                                 os << "<![CDATA[";
1552                                         else
1553                                           lines += sgml::openTag(os, depth + command_depth, mixcont, style->latexparam());
1554                                 }
1555                                 break;
1556                         }
1557
1558                         desc_on = (style->labeltype == LABEL_MANUAL);
1559
1560                         environment_inner[depth] = desc_on ? "varlistentry" : "listitem";
1561                         lines += sgml::openTag(os, depth + 1 + command_depth, mixcont, environment_inner[depth]);
1562
1563                         item_name = desc_on ? "term" : "para";
1564                         lines += sgml::openTag(os, depth + 1 + command_depth, mixcont, item_name);
1565
1566                         break;
1567                 default:
1568                         lines += sgml::openTag(os, depth + command_depth, mixcont, style->latexname());
1569                         break;
1570                 }
1571
1572                 buf->simpleDocBookOnePar(os, pit, desc_on, depth + 1 + command_depth);
1573
1574                 string end_tag;
1575                 // write closing SGML tags
1576                 switch (style->latextype) {
1577                 case LATEX_ENVIRONMENT:
1578                         if (!style->latexparam().empty()) {
1579                                 if (style->latexparam() == "CDATA")
1580                                         os << "]]>";
1581                                 else
1582                                         lines += sgml::closeTag(os, depth + command_depth, mixcont, style->latexparam());
1583                         }
1584                         break;
1585                 case LATEX_ITEM_ENVIRONMENT:
1586                         if (desc_on == 1) break;
1587                         end_tag= "para";
1588                         lines += sgml::closeTag(os, depth + 1 + command_depth, mixcont, end_tag);
1589                         break;
1590                 case LATEX_PARAGRAPH:
1591                         lines += sgml::closeTag(os, depth + command_depth, mixcont, style->latexname());
1592                         break;
1593                 default:
1594                         lines += sgml::closeTag(os, depth + command_depth, mixcont, style->latexname());
1595                         break;
1596                 }
1597         }
1598
1599         // Close open tags
1600         for (int d = depth; d >= 0; --d) {
1601                 if (!environment_stack[depth].empty()) {
1602                         if (environment_inner[depth] != "!-- --") {
1603                                 item_name = "listitem";
1604                                 lines += sgml::closeTag(os, command_depth + depth, mixcont, item_name);
1605                                if (environment_inner[depth] == "varlistentry")
1606                                        lines += sgml::closeTag(os, depth + command_depth, mixcont, environment_inner[depth]);
1607                         }
1608
1609                         lines += sgml::closeTag(os, depth + command_depth, mixcont, environment_stack[depth]);
1610                 }
1611         }
1612
1613         return lines;
1614 }
1615
1616
1617 void InsetText::validate(LaTeXFeatures & features) const
1618 {
1619         for_each(paragraphs.begin(), paragraphs.end(),
1620                  boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1621 }
1622
1623
1624 void InsetText::getCursor(BufferView & bv, int & x, int & y) const
1625 {
1626         if (the_locking_inset) {
1627                 the_locking_inset->getCursor(bv, x, y);
1628                 return;
1629         }
1630         x = cx(&bv);
1631         y = cy(&bv) + InsetText::y();
1632 }
1633
1634
1635 void InsetText::getCursorPos(BufferView * bv, int & x, int & y) const
1636 {
1637         if (the_locking_inset) {
1638                 the_locking_inset->getCursorPos(bv, x, y);
1639                 return;
1640         }
1641         x = cx(bv) - top_x - TEXT_TO_INSET_OFFSET;
1642         y = cy(bv) - TEXT_TO_INSET_OFFSET;
1643 }
1644
1645
1646 int InsetText::insetInInsetY() const
1647 {
1648         if (!the_locking_inset)
1649                 return 0;
1650
1651         return (inset_y + the_locking_inset->insetInInsetY());
1652 }
1653
1654
1655 void InsetText::fitInsetCursor(BufferView * bv) const
1656 {
1657         if (the_locking_inset) {
1658                 the_locking_inset->fitInsetCursor(bv);
1659                 return;
1660         }
1661         LyXFont const font =
1662                 getLyXText(bv)->getFont(bv->buffer(), cpar(bv), cpos(bv));
1663
1664         int const asc = font_metrics::maxAscent(font);
1665         int const desc = font_metrics::maxDescent(font);
1666
1667         if (bv->fitLockedInsetCursor(cx(bv), cy(bv), asc, desc))
1668                 need_update |= FULL;
1669 }
1670
1671
1672 Inset::RESULT
1673 InsetText::moveRight(BufferView * bv, bool activate_inset, bool selecting)
1674 {
1675         if (getLyXText(bv)->cursor.par()->isRightToLeftPar(bv->buffer()->params))
1676                 return moveLeftIntern(bv, false, activate_inset, selecting);
1677         else
1678                 return moveRightIntern(bv, true, activate_inset, selecting);
1679 }
1680
1681
1682 Inset::RESULT
1683 InsetText::moveLeft(BufferView * bv, bool activate_inset, bool selecting)
1684 {
1685         if (getLyXText(bv)->cursor.par()->isRightToLeftPar(bv->buffer()->params))
1686                 return moveRightIntern(bv, true, activate_inset, selecting);
1687         else
1688                 return moveLeftIntern(bv, false, activate_inset, selecting);
1689 }
1690
1691
1692 Inset::RESULT
1693 InsetText::moveRightIntern(BufferView * bv, bool front,
1694                            bool activate_inset, bool selecting)
1695 {
1696         LyXText * text = getLyXText(bv);
1697
1698         ParagraphList::iterator c_par = cpar(bv);
1699
1700         if (boost::next(c_par) == paragraphs.end() &&
1701             (cpos(bv) >= c_par->size()))
1702                 return FINISHED_RIGHT;
1703         if (activate_inset && checkAndActivateInset(bv, front))
1704                 return DISPATCHED;
1705         text->cursorRight(bv);
1706         if (!selecting)
1707                 text->clearSelection();
1708         return DISPATCHED_NOUPDATE;
1709 }
1710
1711
1712 Inset::RESULT
1713 InsetText::moveLeftIntern(BufferView * bv, bool front,
1714                           bool activate_inset, bool selecting)
1715 {
1716         LyXText * text = getLyXText(bv);
1717
1718         if (cpar(bv) == paragraphs.begin() && (cpos(bv) <= 0))
1719                 return FINISHED;
1720         text->cursorLeft(bv);
1721         if (!selecting)
1722                 text->clearSelection();
1723         if (activate_inset && checkAndActivateInset(bv, front))
1724                 return DISPATCHED;
1725         return DISPATCHED_NOUPDATE;
1726 }
1727
1728
1729 Inset::RESULT InsetText::moveUp(BufferView * bv)
1730 {
1731         if (crow(bv) == getLyXText(bv)->rows().begin())
1732                 return FINISHED_UP;
1733         getLyXText(bv)->cursorUp(bv);
1734         getLyXText(bv)->clearSelection();
1735         return DISPATCHED_NOUPDATE;
1736 }
1737
1738
1739 Inset::RESULT InsetText::moveDown(BufferView * bv)
1740 {
1741         if (boost::next(crow(bv)) == getLyXText(bv)->rows().end())
1742                 return FINISHED_DOWN;
1743         getLyXText(bv)->cursorDown(bv);
1744         getLyXText(bv)->clearSelection();
1745         return DISPATCHED_NOUPDATE;
1746 }
1747
1748
1749 bool InsetText::insertInset(BufferView * bv, Inset * inset)
1750 {
1751         if (the_locking_inset) {
1752                 if (the_locking_inset->insetAllowed(inset))
1753                         return the_locking_inset->insertInset(bv, inset);
1754                 return false;
1755         }
1756         inset->setOwner(this);
1757         getLyXText(bv)->insertInset(inset);
1758         bv->fitCursor();
1759         updateLocal(bv, CURSOR_PAR|CURSOR, true);
1760         return true;
1761 }
1762
1763
1764 bool InsetText::insetAllowed(Inset::Code code) const
1765 {
1766         // in_insetAllowed is a really gross hack,
1767         // to allow us to call the owner's insetAllowed
1768         // without stack overflow, which can happen
1769         // when the owner uses InsetCollapsable::insetAllowed()
1770         bool ret = true;
1771         if (in_insetAllowed)
1772                 return ret;
1773         in_insetAllowed = true;
1774         if (the_locking_inset)
1775                 ret = the_locking_inset->insetAllowed(code);
1776         else if (owner())
1777                 ret = owner()->insetAllowed(code);
1778         in_insetAllowed = false;
1779         return ret;
1780 }
1781
1782
1783 UpdatableInset * InsetText::getLockingInset() const
1784 {
1785         return the_locking_inset ? the_locking_inset->getLockingInset() :
1786                 const_cast<InsetText *>(this);
1787 }
1788
1789
1790 UpdatableInset * InsetText::getFirstLockingInsetOfType(Inset::Code c)
1791 {
1792         if (c == lyxCode())
1793                 return this;
1794         if (the_locking_inset)
1795                 return the_locking_inset->getFirstLockingInsetOfType(c);
1796         return 0;
1797 }
1798
1799
1800 bool InsetText::showInsetDialog(BufferView * bv) const
1801 {
1802         if (the_locking_inset)
1803                 return the_locking_inset->showInsetDialog(bv);
1804         return false;
1805 }
1806
1807
1808 void InsetText::getLabelList(std::vector<string> & list) const
1809 {
1810         ParagraphList::const_iterator pit = paragraphs.begin();
1811         ParagraphList::const_iterator pend = paragraphs.end();
1812         for (; pit != pend; ++pit) {
1813                 InsetList::const_iterator beg = pit->insetlist.begin();
1814                 InsetList::const_iterator end = pit->insetlist.end();
1815                 for (; beg != end; ++beg)
1816                         beg->inset->getLabelList(list);
1817         }
1818 }
1819
1820
1821 void InsetText::setFont(BufferView * bv, LyXFont const & font, bool toggleall,
1822                         bool selectall)
1823 {
1824         if (the_locking_inset) {
1825                 the_locking_inset->setFont(bv, font, toggleall, selectall);
1826                 return;
1827         }
1828
1829         if ((paragraphs.size() == 1 && paragraphs.begin()->empty())
1830             || cpar(bv)->empty()) {
1831                 getLyXText(bv)->setFont(font, toggleall);
1832                 return;
1833         }
1834
1835         bool clear = false;
1836         if (!lt) {
1837                 lt = getLyXText(bv);
1838                 clear = true;
1839         }
1840
1841         if (lt->selection.set()) {
1842                 setUndo(bv, Undo::EDIT, lt->cursor.par());
1843         }
1844
1845         if (selectall)
1846                 selectAll(bv);
1847
1848         lt->toggleFree(font, toggleall);
1849
1850         if (selectall)
1851                 lt->clearSelection();
1852
1853         bv->fitCursor();
1854
1855         bool flag = (selectall || lt->selection.set());
1856
1857         if (clear)
1858                 lt = 0;
1859
1860         if (flag)
1861                 updateLocal(bv, FULL, true);
1862         else
1863                 updateLocal(bv, CURSOR_PAR, true);
1864 }
1865
1866
1867 bool InsetText::checkAndActivateInset(BufferView * bv, bool front)
1868 {
1869         if (cpar(bv)->isInset(cpos(bv))) {
1870                 Inset * inset =
1871                         static_cast<UpdatableInset*>(cpar(bv)->getInset(cpos(bv)));
1872                 if (!isHighlyEditableInset(inset))
1873                         return false;
1874                 FuncRequest cmd(bv, LFUN_INSET_EDIT, front ? "left" : "right");
1875                 inset->localDispatch(cmd);
1876                 if (!the_locking_inset)
1877                         return false;
1878                 updateLocal(bv, CURSOR, false);
1879                 return true;
1880         }
1881         return false;
1882 }
1883
1884
1885 bool InsetText::checkAndActivateInset(BufferView * bv, int x, int y,
1886                                       mouse_button::state button)
1887 {
1888         x -= drawTextXOffset;
1889         int dummyx = x;
1890         int dummyy = y + dim_.asc;
1891         Inset * inset = getLyXText(bv)->checkInsetHit(dummyx, dummyy);
1892         // we only do the edit() call if the inset was hit by the mouse
1893         // or if it is a highly editable inset. So we should call this
1894         // function from our own edit with button < 0.
1895         // FIXME: GUII jbl. I've changed this to ::none for now which is probably
1896         // WRONG
1897         if (button == mouse_button::none && !isHighlyEditableInset(inset))
1898                 return false;
1899
1900         if (inset) {
1901                 if (x < 0)
1902                         x = dim_.wid;
1903                 if (y < 0)
1904                         y = dim_.des;
1905                 inset_x = cix(bv) - top_x + drawTextXOffset;
1906                 inset_y = ciy(bv) + drawTextYOffset;
1907                 FuncRequest cmd(bv, LFUN_INSET_EDIT, x - inset_x, y - inset_y, button);
1908                 inset->localDispatch(cmd);
1909                 if (!the_locking_inset)
1910                         return false;
1911                 updateLocal(bv, CURSOR, false);
1912                 return true;
1913         }
1914         return false;
1915 }
1916
1917
1918 int InsetText::getMaxWidth(BufferView * bv, UpdatableInset const * inset) const
1919 {
1920 #if 0
1921         int w = UpdatableInset::getMaxWidth(bv, inset);
1922         if (w < 0) {
1923                 return -1;
1924         }
1925         if (owner()) {
1926                 w = w - top_x + owner()->x();
1927                 return w;
1928         }
1929         w -= (2 * TEXT_TO_INSET_OFFSET);
1930         return w - top_x;
1931 #else
1932         return UpdatableInset::getMaxWidth(bv, inset);
1933 #endif
1934 }
1935
1936
1937 void InsetText::setParagraphData(ParagraphList const & plist)
1938 {
1939         // we have to unlock any locked inset otherwise we're in troubles
1940         the_locking_inset = 0;
1941
1942         // But it it makes no difference that is a lot better.
1943 #warning FIXME.
1944         // See if this can be simplified when std::list is in effect.
1945         paragraphs.clear();
1946
1947         ParagraphList::const_iterator it = plist.begin();
1948         ParagraphList::const_iterator end = plist.end();
1949         for (; it != end; ++it) {
1950                 paragraphs.push_back(*it);
1951                 Paragraph & tmp = paragraphs.back();
1952                 tmp.setInsetOwner(this);
1953         }
1954
1955         reinitLyXText();
1956         need_update = INIT;
1957 }
1958
1959
1960 void InsetText::markNew(bool track_changes)
1961 {
1962         ParagraphList::iterator pit = paragraphs.begin();
1963         ParagraphList::iterator pend = paragraphs.end();
1964         for (; pit != pend; ++pit) {
1965                 if (track_changes) {
1966                         pit->trackChanges();
1967                 } else {
1968                         // no-op when not tracking
1969                         pit->cleanChanges();
1970                 }
1971         }
1972 }
1973
1974
1975 void InsetText::setText(string const & data, LyXFont const & font)
1976 {
1977         clear(false);
1978         for (unsigned int i = 0; i < data.length(); ++i)
1979                 paragraphs.begin()->insertChar(i, data[i], font);
1980         reinitLyXText();
1981 }
1982
1983
1984 void InsetText::setAutoBreakRows(bool flag)
1985 {
1986         if (flag != autoBreakRows) {
1987                 autoBreakRows = flag;
1988                 if (!flag)
1989                         removeNewlines();
1990                 need_update = INIT;
1991         }
1992 }
1993
1994
1995 void InsetText::setDrawFrame(BufferView * bv, DrawFrame how)
1996 {
1997         if (how != drawFrame_) {
1998                 drawFrame_ = how;
1999                 if (bv)
2000                         updateLocal(bv, DRAW_FRAME, false);
2001         }
2002 }
2003
2004
2005 void InsetText::setFrameColor(BufferView * bv, LColor::color col)
2006 {
2007         if (frame_color != col) {
2008                 frame_color = col;
2009                 if (bv)
2010                         updateLocal(bv, DRAW_FRAME, false);
2011         }
2012 }
2013
2014
2015 int InsetText::cx(BufferView * bv) const
2016 {
2017         // we do nothing dangerous so we use a local cache
2018         LyXText * llt = getLyXText(bv);
2019         int x = llt->cursor.x() + top_x + TEXT_TO_INSET_OFFSET;
2020         if (the_locking_inset) {
2021                 LyXFont font = llt->getFont(bv->buffer(), llt->cursor.par(),
2022                                             llt->cursor.pos());
2023                 if (font.isVisibleRightToLeft())
2024                         x -= the_locking_inset->width(bv, font);
2025         }
2026         return x;
2027 }
2028
2029
2030 int InsetText::cix(BufferView * bv) const
2031 {
2032         // we do nothing dangerous so we use a local cache
2033         LyXText * llt = getLyXText(bv);
2034         int x = llt->cursor.ix() + top_x + TEXT_TO_INSET_OFFSET;
2035         if (the_locking_inset) {
2036                 LyXFont font = llt->getFont(bv->buffer(), llt->cursor.par(),
2037                                             llt->cursor.pos());
2038                 if (font.isVisibleRightToLeft())
2039                         x -= the_locking_inset->width(bv, font);
2040         }
2041         return x;
2042 }
2043
2044
2045 int InsetText::cy(BufferView * bv) const
2046 {
2047         LyXFont font;
2048         return getLyXText(bv)->cursor.y() - ascent(bv, font) + TEXT_TO_INSET_OFFSET;
2049 }
2050
2051
2052 int InsetText::ciy(BufferView * bv) const
2053 {
2054         LyXFont font;
2055         return getLyXText(bv)->cursor.iy() - ascent(bv, font) + TEXT_TO_INSET_OFFSET;
2056 }
2057
2058
2059 pos_type InsetText::cpos(BufferView * bv) const
2060 {
2061         return getLyXText(bv)->cursor.pos();
2062 }
2063
2064
2065 ParagraphList::iterator InsetText::cpar(BufferView * bv) const
2066 {
2067         return getLyXText(bv)->cursor.par();
2068 }
2069
2070
2071 bool InsetText::cboundary(BufferView * bv) const
2072 {
2073         return getLyXText(bv)->cursor.boundary();
2074 }
2075
2076
2077 RowList::iterator InsetText::crow(BufferView * bv) const
2078 {
2079         return getLyXText(bv)->cursor.row();
2080 }
2081
2082
2083 LyXText * InsetText::getLyXText(BufferView const * lbv,
2084                                 bool const recursive) const
2085 {
2086         if (cached_bview == lbv) {
2087                 if (recursive && the_locking_inset)
2088                         return the_locking_inset->getLyXText(lbv, true);
2089                 LyXText * lt = cached_text.get();
2090                 lyx::Assert(lt && lt->rows().begin()->par() == const_cast<ParagraphList&>(paragraphs).begin());
2091                 return lt;
2092         }
2093         // Super UGLY! (Lgb)
2094         BufferView * bv = const_cast<BufferView *>(lbv);
2095
2096         cached_bview = bv;
2097         Cache::iterator it = cache.find(bv);
2098
2099         if (it != cache.end()) {
2100                 if (do_reinit) {
2101                         reinitLyXText();
2102                 } else if (do_resize) {
2103                         resizeLyXText(do_resize);
2104                 } else {
2105                         if (lt || !it->second.remove) {
2106                                 lyx::Assert(it->second.text.get());
2107                                 cached_text = it->second.text;
2108                                 if (recursive && the_locking_inset) {
2109                                         return the_locking_inset->getLyXText(bv, true);
2110                                 }
2111                                 return cached_text.get();
2112                         } else if (it->second.remove) {
2113                                 if (locked) {
2114                                         saveLyXTextState(it->second.text.get());
2115                                 } else {
2116                                         sstate.lpar = const_cast<ParagraphList&>(paragraphs).end();
2117                                 }
2118                         }
2119                         //
2120                         // when we have to reinit the existing LyXText!
2121                         //
2122                         it->second.text->init(bv);
2123                         restoreLyXTextState(it->second.text.get());
2124                         it->second.remove = false;
2125                 }
2126                 cached_text = it->second.text;
2127                 if (the_locking_inset && recursive) {
2128                         return the_locking_inset->getLyXText(bv);
2129                 }
2130                 return cached_text.get();
2131         }
2132         ///
2133         // we are here only if we don't have a BufferView * in the cache!!!
2134         ///
2135         cached_text.reset(new LyXText(bv, const_cast<InsetText *>(this)));
2136         cached_text->init(bv);
2137         restoreLyXTextState(cached_text.get());
2138
2139         cache.insert(make_pair(bv, cached_text));
2140
2141         if (the_locking_inset && recursive) {
2142                 return the_locking_inset->getLyXText(bv);
2143         }
2144         return cached_text.get();
2145 }
2146
2147
2148 void InsetText::deleteLyXText(BufferView * bv, bool recursive) const
2149 {
2150         cached_bview = 0;
2151
2152         Cache::iterator it = cache.find(bv);
2153
2154         if (it == cache.end()) {
2155                 return;
2156         }
2157
2158         lyx::Assert(it->second.text.get());
2159
2160         it->second.remove = true;
2161         if (recursive) {
2162                 /// then remove all LyXText in text-insets
2163                 for_each(const_cast<ParagraphList&>(paragraphs).begin(),
2164                          const_cast<ParagraphList&>(paragraphs).end(),
2165                          boost::bind(&Paragraph::deleteInsetsLyXText, _1, bv));
2166         }
2167 }
2168
2169
2170 void InsetText::resizeLyXText(BufferView * bv, bool force) const
2171 {
2172         if (lt) {
2173                 // we cannot resize this because we are in use!
2174                 // so do this on the next possible getLyXText()
2175                 do_resize = bv;
2176                 return;
2177         }
2178         do_resize = 0;
2179         if (paragraphs.size() == 1 && paragraphs.begin()->empty()) {
2180                 // no data, resize not neccessary!
2181                 // we have to do this as a fixed width may have changed!
2182                 LyXText * t = getLyXText(bv);
2183                 saveLyXTextState(t);
2184                 t->init(bv, true);
2185                 restoreLyXTextState(t);
2186                 return;
2187         }
2188
2189         // one endless line, resize normally not necessary
2190         if (!force && getMaxWidth(bv, this) < 0)
2191                 return;
2192
2193         Cache::iterator it = cache.find(bv);
2194         if (it == cache.end()) {
2195                 return;
2196         }
2197
2198         lyx::Assert(it->second.text.get());
2199
2200         LyXText * t = it->second.text.get();
2201         saveLyXTextState(t);
2202
2203         for_each(const_cast<ParagraphList&>(paragraphs).begin(),
2204                  const_cast<ParagraphList&>(paragraphs).end(),
2205                  boost::bind(&Paragraph::resizeInsetsLyXText, _1, bv));
2206
2207         t->init(bv, true);
2208         restoreLyXTextState(t);
2209
2210         if (the_locking_inset) {
2211                 inset_x = cix(bv) - top_x + drawTextXOffset;
2212                 inset_y = ciy(bv) + drawTextYOffset;
2213         }
2214
2215         t->top_y(bv->screen().topCursorVisible(t->cursor, t->top_y()));
2216         if (!owner()) {
2217                 const_cast<InsetText*>(this)->updateLocal(bv, FULL, false);
2218                 // this will scroll the screen such that the cursor becomes visible
2219                 bv->updateScrollbar();
2220         } else {
2221                 need_update |= FULL;
2222         }
2223 }
2224
2225
2226 void InsetText::reinitLyXText() const
2227 {
2228         if (lt) {
2229                 // we cannot resize this because we are in use!
2230                 // so do this on the next possible getLyXText()
2231                 do_reinit = true;
2232                 return;
2233         }
2234         do_reinit = false;
2235         do_resize = 0;
2236         for (Cache::iterator it = cache.begin(); it != cache.end(); ++it) {
2237                 lyx::Assert(it->second.text.get());
2238
2239                 LyXText * t = it->second.text.get();
2240                 BufferView * bv = it->first;
2241
2242                 saveLyXTextState(t);
2243
2244                 for_each(const_cast<ParagraphList&>(paragraphs).begin(),
2245                          const_cast<ParagraphList&>(paragraphs).end(),
2246                          boost::bind(&Paragraph::resizeInsetsLyXText, _1, bv));
2247
2248                 t->init(bv, true);
2249                 restoreLyXTextState(t);
2250                 if (the_locking_inset) {
2251                         inset_x = cix(bv) - top_x + drawTextXOffset;
2252                         inset_y = ciy(bv) + drawTextYOffset;
2253                 }
2254                 t->top_y(bv->screen().topCursorVisible(t->cursor, t->top_y()));
2255                 if (!owner()) {
2256                         const_cast<InsetText*>(this)->updateLocal(bv, FULL, false);
2257                         // this will scroll the screen such that the cursor becomes visible
2258                         bv->updateScrollbar();
2259                 } else {
2260                         need_update = FULL;
2261                 }
2262         }
2263 }
2264
2265
2266 void InsetText::removeNewlines()
2267 {
2268         bool changed = false;
2269
2270         ParagraphList::iterator it = paragraphs.begin();
2271         ParagraphList::iterator end = paragraphs.end();
2272         for (; it != end; ++it) {
2273                 for (int i = 0; i < it->size(); ++i) {
2274                         if (it->isNewline(i)) {
2275                                 changed = true;
2276                                 it->erase(i);
2277                         }
2278                 }
2279         }
2280         if (changed)
2281                 reinitLyXText();
2282 }
2283
2284
2285 bool InsetText::nodraw() const
2286 {
2287         if (the_locking_inset)
2288                 return the_locking_inset->nodraw();
2289         return UpdatableInset::nodraw();
2290 }
2291
2292
2293 int InsetText::scroll(bool recursive) const
2294 {
2295         int sx = UpdatableInset::scroll(false);
2296
2297         if (recursive && the_locking_inset)
2298                 sx += the_locking_inset->scroll(recursive);
2299
2300         return sx;
2301 }
2302
2303
2304 void InsetText::selectAll(BufferView * bv)
2305 {
2306         getLyXText(bv)->cursorTop();
2307         getLyXText(bv)->selection.cursor = getLyXText(bv)->cursor;
2308         getLyXText(bv)->cursorBottom();
2309         getLyXText(bv)->setSelection();
2310 }
2311
2312
2313 void InsetText::clearSelection(BufferView * bv)
2314 {
2315         getLyXText(bv)->clearSelection();
2316 }
2317
2318
2319 void InsetText::clearInset(BufferView * bv, int start_x, int baseline) const
2320 {
2321         Painter & pain = bv->painter();
2322         int w = dim_.wid;
2323         int h = dim_.asc + dim_.des;
2324         int ty = baseline - dim_.asc;
2325
2326         if (ty < 0) {
2327                 h += ty;
2328                 ty = 0;
2329         }
2330         if ((ty + h) > pain.paperHeight())
2331                 h = pain.paperHeight();
2332         if ((top_x + drawTextXOffset + w) > pain.paperWidth())
2333                 w = pain.paperWidth();
2334         pain.fillRectangle(start_x + 1, ty + 1, w - 3, h - 1, backgroundColor());
2335         need_update = FULL;
2336 }
2337
2338
2339 ParagraphList * InsetText::getParagraphs(int i) const
2340 {
2341         return (i == 0) ? const_cast<ParagraphList*>(&paragraphs) : 0;
2342 }
2343
2344
2345 LyXCursor const & InsetText::cursor(BufferView * bv) const
2346 {
2347         if (the_locking_inset)
2348                 return the_locking_inset->cursor(bv);
2349         return getLyXText(bv)->cursor;
2350 }
2351
2352
2353 Inset * InsetText::getInsetFromID(int id_arg) const
2354 {
2355         if (id_arg == id())
2356                 return const_cast<InsetText *>(this);
2357
2358         ParagraphList::const_iterator pit = paragraphs.begin();
2359         ParagraphList::const_iterator pend = paragraphs.end();
2360         for (; pit != pend; ++pit) {
2361                 InsetList::const_iterator it = pit->insetlist.begin();
2362                 InsetList::const_iterator end = pit->insetlist.end();
2363                 for (; it != end; ++it) {
2364                         if (it->inset->id() == id_arg)
2365                                 return it->inset;
2366                         Inset * in = it->inset->getInsetFromID(id_arg);
2367                         if (in)
2368                                 return in;
2369                 }
2370         }
2371         return 0;
2372 }
2373
2374
2375 WordLangTuple const
2376 InsetText::selectNextWordToSpellcheck(BufferView * bv,
2377                                       float & value) const
2378 {
2379         bool clear = false;
2380         WordLangTuple word;
2381
2382         if (!lt) {
2383                 lt = getLyXText(bv);
2384                 clear = true;
2385         }
2386         if (the_locking_inset) {
2387                 word = the_locking_inset->selectNextWordToSpellcheck(bv, value);
2388                 if (!word.word().empty()) {
2389                         value += cy(bv);
2390                         if (clear)
2391                                 lt = 0;
2392                         return word;
2393                 }
2394                 // we have to go on checking so move cursor to the next char
2395                 lt->cursor.pos(lt->cursor.pos() + 1);
2396         }
2397         word = lt->selectNextWordToSpellcheck(value);
2398         if (word.word().empty())
2399                 bv->unlockInset(const_cast<InsetText *>(this));
2400         else
2401                 value = cy(bv);
2402         if (clear)
2403                 lt = 0;
2404         return word;
2405 }
2406
2407
2408 void InsetText::selectSelectedWord(BufferView * bv)
2409 {
2410         if (the_locking_inset) {
2411                 the_locking_inset->selectSelectedWord(bv);
2412                 return;
2413         }
2414         getLyXText(bv)->selectSelectedWord();
2415         updateLocal(bv, SELECTION, false);
2416 }
2417
2418
2419 void InsetText::toggleSelection(BufferView * bv, bool kill_selection)
2420 {
2421         if (the_locking_inset) {
2422                 the_locking_inset->toggleSelection(bv, kill_selection);
2423         }
2424         bool clear = false;
2425         if (!lt) {
2426                 lt = getLyXText(bv);
2427                 clear = true;
2428         }
2429
2430         int x = top_x + TEXT_TO_INSET_OFFSET;
2431
2432         RowList::iterator rowit = lt->rows().begin();
2433         RowList::iterator end = lt->rows().end();
2434         int y_offset = top_baseline - rowit->ascent_of_text();
2435         int y = y_offset;
2436         while ((rowit != end) && ((y + rowit->height()) <= 0)) {
2437                 y += rowit->height();
2438                 ++rowit;
2439         }
2440         if (y_offset < 0)
2441                 y_offset = y;
2442
2443         if (need_update & SELECTION)
2444                 need_update = NONE;
2445         bv->screen().toggleSelection(lt, bv, kill_selection, y_offset, x);
2446         if (clear)
2447                 lt = 0;
2448 }
2449
2450
2451 bool InsetText::nextChange(BufferView * bv, lyx::pos_type & length)
2452 {
2453         bool clear = false;
2454         if (!lt) {
2455                 lt = getLyXText(bv);
2456                 clear = true;
2457         }
2458         if (the_locking_inset) {
2459                 if (the_locking_inset->nextChange(bv, length))
2460                         return true;
2461                 lt->cursorRight(true);
2462         }
2463         lyxfind::SearchResult result =
2464                 lyxfind::findNextChange(bv, lt, length);
2465
2466         if (result == lyxfind::SR_FOUND) {
2467                 LyXCursor cur = lt->cursor;
2468                 bv->unlockInset(bv->theLockingInset());
2469                 if (bv->lockInset(this))
2470                         locked = true;
2471                 lt->cursor = cur;
2472                 lt->setSelectionRange(length);
2473                 updateLocal(bv, SELECTION, false);
2474         }
2475         if (clear)
2476                 lt = 0;
2477         return result != lyxfind::SR_NOT_FOUND;
2478 }
2479
2480
2481 bool InsetText::searchForward(BufferView * bv, string const & str,
2482                               bool cs, bool mw)
2483 {
2484         bool clear = false;
2485         if (!lt) {
2486                 lt = getLyXText(bv);
2487                 clear = true;
2488         }
2489         if (the_locking_inset) {
2490                 if (the_locking_inset->searchForward(bv, str, cs, mw))
2491                         return true;
2492                 lt->cursorRight(true);
2493         }
2494         lyxfind::SearchResult result =
2495                 lyxfind::LyXFind(bv, lt, str, true, cs, mw);
2496
2497         if (result == lyxfind::SR_FOUND) {
2498                 LyXCursor cur = lt->cursor;
2499                 bv->unlockInset(bv->theLockingInset());
2500                 if (bv->lockInset(this))
2501                         locked = true;
2502                 lt->cursor = cur;
2503                 lt->setSelectionRange(str.length());
2504                 updateLocal(bv, SELECTION, false);
2505         }
2506         if (clear)
2507                 lt = 0;
2508         return (result != lyxfind::SR_NOT_FOUND);
2509 }
2510
2511 bool InsetText::searchBackward(BufferView * bv, string const & str,
2512                                bool cs, bool mw)
2513 {
2514         if (the_locking_inset) {
2515                 if (the_locking_inset->searchBackward(bv, str, cs, mw))
2516                         return true;
2517         }
2518         bool clear = false;
2519         if (!lt) {
2520                 lt = getLyXText(bv);
2521                 clear = true;
2522         }
2523         if (!locked) {
2524                 ParagraphList::iterator pit = paragraphs.begin();
2525                 ParagraphList::iterator pend = paragraphs.end();
2526
2527                 while (boost::next(pit) != pend)
2528                         ++pit;
2529
2530                 lt->setCursor(pit, pit->size());
2531         }
2532         lyxfind::SearchResult result =
2533                 lyxfind::LyXFind(bv, lt, str, false, cs, mw);
2534
2535         if (result == lyxfind::SR_FOUND) {
2536                 LyXCursor cur = lt->cursor;
2537                 bv->unlockInset(bv->theLockingInset());
2538                 if (bv->lockInset(this))
2539                         locked = true;
2540                 lt->cursor = cur;
2541                 lt->setSelectionRange(str.length());
2542                 updateLocal(bv, SELECTION, false);
2543         }
2544         if (clear)
2545                 lt = 0;
2546         return (result != lyxfind::SR_NOT_FOUND);
2547 }
2548
2549
2550 bool InsetText::checkInsertChar(LyXFont & font)
2551 {
2552         if (owner())
2553                 return owner()->checkInsertChar(font);
2554         return true;
2555 }
2556
2557
2558 void InsetText::collapseParagraphs(BufferView * bv)
2559 {
2560         LyXText * llt = getLyXText(bv);
2561
2562         while (paragraphs.size() > 1) {
2563                 ParagraphList::iterator first_par = paragraphs.begin();
2564                 ParagraphList::iterator next_par = boost::next(first_par);
2565                 size_t const first_par_size = first_par->size();
2566
2567                 if (!first_par->empty() &&
2568                     !next_par->empty() &&
2569                     !first_par->isSeparator(first_par_size - 1)) {
2570                         first_par->insertChar(first_par_size, ' ');
2571                 }
2572
2573                 if (llt->selection.set()) {
2574                         if (llt->selection.start.par() == next_par) {
2575                                 llt->selection.start.par(first_par);
2576                                 llt->selection.start.pos(
2577                                         llt->selection.start.pos() + first_par_size);
2578                         }
2579                         if (llt->selection.end.par() == next_par) {
2580                                 llt->selection.end.par(first_par);
2581                                 llt->selection.end.pos(
2582                                         llt->selection.end.pos() + first_par_size);
2583                         }
2584                 }
2585
2586                 mergeParagraph(bv->buffer()->params, paragraphs, first_par);
2587         }
2588         reinitLyXText();
2589 }
2590
2591
2592 void InsetText::getDrawFont(LyXFont & font) const
2593 {
2594         if (!owner())
2595                 return;
2596         owner()->getDrawFont(font);
2597 }
2598
2599
2600 void InsetText::appendParagraphs(Buffer * buffer, ParagraphList & plist)
2601 {
2602 #warning FIXME Check if Changes stuff needs changing here. (Lgb)
2603 // And it probably does. You have to take a look at this John. (Lgb)
2604 #warning John, have a look here. (Lgb)
2605         ParagraphList::iterator pit = plist.begin();
2606         ParagraphList::iterator ins = paragraphs.insert(paragraphs.end(), *pit);
2607         ++pit;
2608         mergeParagraph(buffer->params, paragraphs, boost::prior(ins));
2609
2610         ParagraphList::iterator pend = plist.end();
2611         for (; pit != pend; ++pit) {
2612                 paragraphs.push_back(*pit);
2613         }
2614
2615         reinitLyXText();
2616 }
2617
2618
2619 void InsetText::addPreview(grfx::PreviewLoader & loader) const
2620 {
2621         ParagraphList::const_iterator pit = paragraphs.begin();
2622         ParagraphList::const_iterator pend = paragraphs.end();
2623
2624         for (; pit != pend; ++pit) {
2625                 InsetList::const_iterator it  = pit->insetlist.begin();
2626                 InsetList::const_iterator end = pit->insetlist.end();
2627                 for (; it != end; ++it) {
2628                         it->inset->addPreview(loader);
2629                 }
2630         }
2631 }