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