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