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