]> git.lyx.org Git - lyx.git/blob - src/insets/insettext.C
Don't remove cell selections after fontchange.
[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         lt->setCursor(bv, par, 0);
757         if (clear)
758                 lt = 0;
759         updateLocal(bv, code, false);
760 }
761
762 void InsetText::lockInset(BufferView * bv, UpdatableInset * inset)
763 {
764         the_locking_inset = inset;
765         inset_x = cx(bv) - top_x + drawTextXOffset;
766         inset_y = cy(bv) + drawTextYOffset;
767         inset_pos = cpos(bv);
768         inset_par = cpar(bv);
769         inset_boundary = cboundary(bv);
770         updateLocal(bv, CURSOR, false);
771 }
772
773
774 bool InsetText::lockInsetInInset(BufferView * bv, UpdatableInset * inset)
775 {
776         lyxerr[Debug::INSETS] << "InsetText::LockInsetInInset("
777                               << inset << "): ";
778         if (!inset)
779                 return false;
780         if (!the_locking_inset) {
781                 Paragraph * p = par;
782                 int const id = inset->id();
783                 while(p) {
784                         Paragraph::inset_iterator it =
785                                 p->inset_iterator_begin();
786                         Paragraph::inset_iterator const end =
787                                 p->inset_iterator_end();
788                         for (; it != end; ++it) {
789                                 if ((*it) == inset) {
790                                         getLyXText(bv)->setCursorIntern(bv, p, it.getPos());
791                                         lockInset(bv, inset);
792                                         return true;
793                                 }
794                                 if ((*it)->getInsetFromID(id)) {
795                                         getLyXText(bv)->setCursorIntern(bv, p, it.getPos());
796                                         (*it)->edit(bv);
797                                         return the_locking_inset->lockInsetInInset(bv, inset);
798                                 }
799                         }
800                         p = p->next();
801                 }
802                 return false;
803         }
804         if (inset == cpar(bv)->getInset(cpos(bv))) {
805                 lyxerr[Debug::INSETS] << "OK" << endl;
806                 lockInset(bv, inset);
807                 return true;
808         } else if (the_locking_inset && (the_locking_inset == inset)) {
809                 if (cpar(bv) == inset_par && cpos(bv) == inset_pos) {
810                         lyxerr[Debug::INSETS] << "OK" << endl;
811                         inset_x = cx(bv) - top_x + drawTextXOffset;
812                         inset_y = cy(bv) + drawTextYOffset;
813                 } else {
814                         lyxerr[Debug::INSETS] << "cursor.pos != inset_pos" << endl;
815                 }
816         } else if (the_locking_inset) {
817                 lyxerr[Debug::INSETS] << "MAYBE" << endl;
818                 return the_locking_inset->lockInsetInInset(bv, inset);
819         }
820         lyxerr[Debug::INSETS] << "NOT OK" << endl;
821         return false;
822 }
823
824
825 bool InsetText::unlockInsetInInset(BufferView * bv, UpdatableInset * inset,
826                                    bool lr)
827 {
828         if (!the_locking_inset)
829                 return false;
830         if (the_locking_inset == inset) {
831                 the_locking_inset->insetUnlock(bv);
832                 getLyXText(bv)->updateInset(bv, inset);
833                 the_locking_inset = 0;
834                 if (lr)
835                         moveRight(bv, false);
836                 old_par = 0; // force layout setting
837                 if (scroll())
838                         scroll(bv, 0.0F);
839                 else
840                         updateLocal(bv, CURSOR, false);
841                 return true;
842         }
843         return the_locking_inset->unlockInsetInInset(bv, inset, lr);
844 }
845
846
847 bool InsetText::updateInsetInInset(BufferView * bv, Inset * inset)
848 {
849         if (!autoBreakRows && par->next())
850                 collapseParagraphs(bv->buffer()->params);
851         if (inset == this)
852                 return true;
853         bool clear = false;
854         if (!lt) {
855                 lt = getLyXText(bv);
856                 clear = true;
857         }
858         if (!the_locking_inset) {
859                 bool found = lt->updateInset(bv, inset);
860                 if (clear)
861                         lt = 0;
862                 if (found)
863                         setUpdateStatus(bv, NONE);
864                 return found;
865         }
866         if (the_locking_inset != inset) {
867                 bool found = the_locking_inset->updateInsetInInset(bv, inset);
868                 if (clear)
869                         lt = 0;
870                 if (found)
871                         setUpdateStatus(bv, CURSOR_PAR);
872                 return found;
873         }
874         bool found = lt->updateInset(bv, inset);
875         if (clear)
876                 lt = 0;
877         if (found) {
878                 setUpdateStatus(bv, CURSOR_PAR);
879                 if (cpar(bv) == inset_par && cpos(bv) == inset_pos) {
880                         inset_x = cx(bv) - top_x + drawTextXOffset;
881                         inset_y = cy(bv) + drawTextYOffset;
882                 }
883         }
884         return found;
885 }
886
887
888 void InsetText::insetButtonPress(BufferView * bv, int x, int y, int button)
889 {
890         no_selection = true;
891
892         // use this to check mouse motion for selection!
893         mouse_x = x;
894         mouse_y = y;
895
896         int tmp_x = x - drawTextXOffset;
897         int tmp_y = y + insetAscent - getLyXText(bv)->first;
898         Inset * inset = bv->checkInsetHit(getLyXText(bv), tmp_x, tmp_y);
899
900         hideInsetCursor(bv);
901         if (the_locking_inset) {
902                 if (the_locking_inset == inset) {
903                         the_locking_inset->insetButtonPress(bv,
904                                                             x - inset_x,
905                                                             y - inset_y,
906                                                             button);
907                         no_selection = false;
908                         return;
909                 } else if (inset) {
910                         // otherwise unlock the_locking_inset and lock the new inset
911                         the_locking_inset->insetUnlock(bv);
912                         inset_x = cx(bv) - top_x + drawTextXOffset;
913                         inset_y = cy(bv) + drawTextYOffset;
914                         the_locking_inset = 0;
915                         inset->insetButtonPress(bv, x - inset_x,
916                                                 y - inset_y, button);
917                         inset->edit(bv, x - inset_x, y - inset_y, button);
918                         if (the_locking_inset)
919                                 updateLocal(bv, CURSOR, false);
920                         no_selection = false;
921                         return;
922                 }
923                 // otherwise only unlock the_locking_inset
924                 the_locking_inset->insetUnlock(bv);
925                 the_locking_inset = 0;
926         }
927         if (bv->theLockingInset()) {
928                 if (isHighlyEditableInset(inset)) {
929                         UpdatableInset * uinset = static_cast<UpdatableInset*>(inset);
930                         inset_x = cx(bv) - top_x + drawTextXOffset;
931                         inset_y = cy(bv) + drawTextYOffset;
932                         inset_pos = cpos(bv);
933                         inset_par = cpar(bv);
934                         inset_boundary = cboundary(bv);
935                         the_locking_inset = uinset;
936                         uinset->insetButtonPress(bv, x - inset_x, y - inset_y,
937                                                  button);
938                         uinset->edit(bv, x - inset_x, y - inset_y, 0);
939                         if (the_locking_inset)
940                                 updateLocal(bv, CURSOR, false);
941                         no_selection = false;
942                         return;
943                 }
944         }
945         if (!inset) { // && (button == 2)) {
946                 bool paste_internally = false;
947                 if ((button == 2) && getLyXText(bv)->selection.set()) {
948                         localDispatch(bv, LFUN_COPY, "");
949                         paste_internally = true;
950                 }
951                 bool clear = false;
952                 if (!lt) {
953                         lt = getLyXText(bv);
954                         clear = true;
955                 }
956
957                 lt->setCursorFromCoordinates(bv, x - drawTextXOffset,
958                                              y + insetAscent);
959                 // set the selection cursor!
960                 lt->selection.cursor = lt->cursor;
961                 lt->cursor.x_fix(lt->cursor.x());
962
963                 if (lt->selection.set()) {
964                         lt->clearSelection();
965                         if (clear)
966                                 lt = 0;
967                         updateLocal(bv, FULL, false);
968                 } else {
969                         lt->clearSelection();
970                         if (clear)
971                                 lt = 0;
972                         updateLocal(bv, CURSOR, false);
973                 }
974                 bv->owner()->setLayout(cpar(bv)->getLayout());
975                 old_par = cpar(bv);
976                 // Insert primary selection with middle mouse
977                 // if there is a local selection in the current buffer,
978                 // insert this
979                 if (button == 2) {
980                         if (paste_internally)
981                                 localDispatch(bv, LFUN_PASTE, "");
982                         else
983                                 localDispatch(bv, LFUN_PASTESELECTION,
984                                               "paragraph");
985                 }
986         } else {
987                 getLyXText(bv)->clearSelection();
988         }
989         showInsetCursor(bv);
990         no_selection = false;
991 }
992
993
994 bool InsetText::insetButtonRelease(BufferView * bv, int x, int y, int button)
995 {
996         if (the_locking_inset) {
997                 return the_locking_inset->insetButtonRelease(bv,
998                                                              x - inset_x, y - inset_y,
999                                                              button);
1000         }
1001         int tmp_x = x - drawTextXOffset;
1002         int tmp_y = y + insetAscent - getLyXText(bv)->first;
1003         Inset * inset = bv->checkInsetHit(getLyXText(bv), tmp_x, tmp_y);
1004         bool ret = false;
1005         if (inset) {
1006                 if (isHighlyEditableInset(inset)) {
1007                         ret = inset->insetButtonRelease(bv, x - inset_x,
1008                                                         y - inset_y, button);
1009                 } else {
1010                         inset_x = cx(bv) - top_x + drawTextXOffset;
1011                         inset_y = cy(bv) + drawTextYOffset;
1012                         ret = inset->insetButtonRelease(bv, x - inset_x,
1013                                                         y - inset_y, button);
1014                         inset->edit(bv, x - inset_x,
1015                                     y - inset_y, button);
1016                 }
1017                 updateLocal(bv, CURSOR_PAR, false);
1018         }
1019         return ret;
1020 }
1021
1022
1023 void InsetText::insetMotionNotify(BufferView * bv, int x, int y, int state)
1024 {
1025         if (no_selection || ((mouse_x == x) && (mouse_y == y)))
1026                 return;
1027         if (the_locking_inset) {
1028                 the_locking_inset->insetMotionNotify(bv, x - inset_x,
1029                                                      y - inset_y,state);
1030                 return;
1031         }
1032         bool clear = false;
1033         if (!lt) {
1034                 lt = getLyXText(bv);
1035                 clear = true;
1036         }
1037         hideInsetCursor(bv);
1038         LyXCursor cur = lt->cursor;
1039         lt->setCursorFromCoordinates(bv, x - drawTextXOffset, y + insetAscent);
1040         if (cur == lt->cursor) {
1041                 if (clear)
1042                         lt = 0;
1043                 return;
1044         }
1045         lt->setSelection(bv);
1046         bool flag = (lt->toggle_cursor.par() != lt->toggle_end_cursor.par() ||
1047                                  lt->toggle_cursor.pos() != lt->toggle_end_cursor.pos());
1048         if (clear)
1049                 lt = 0;
1050         if (flag) {
1051                 updateLocal(bv, SELECTION, false);
1052         }
1053         showInsetCursor(bv);
1054 }
1055
1056
1057 void InsetText::insetKeyPress(XKeyEvent * xke)
1058 {
1059         if (the_locking_inset) {
1060                 the_locking_inset->insetKeyPress(xke);
1061                 return;
1062         }
1063 }
1064
1065
1066 UpdatableInset::RESULT
1067 InsetText::localDispatch(BufferView * bv,
1068                          kb_action action, string const & arg)
1069 {
1070         bool was_empty = par->size() == 0 && !par->next();
1071         no_selection = false;
1072         UpdatableInset::RESULT
1073                 result= UpdatableInset::localDispatch(bv, action, arg);
1074         if (result != UNDISPATCHED) {
1075                 return DISPATCHED;
1076         }
1077
1078         result = DISPATCHED;
1079         if ((action < 0) && arg.empty())
1080                 return FINISHED;
1081
1082         if (the_locking_inset) {
1083                 result = the_locking_inset->localDispatch(bv, action, arg);
1084                 if (result == DISPATCHED_NOUPDATE)
1085                         return result;
1086                 else if (result == DISPATCHED) {
1087                         updateLocal(bv, CURSOR_PAR, false);
1088                         return result;
1089                 } else if (result >= FINISHED) {
1090                         switch (result) {
1091                         case FINISHED_RIGHT:
1092                                 moveRightIntern(bv, false, false);
1093                                 result = DISPATCHED;
1094                                 break;
1095                         case FINISHED_UP:
1096                                 if ((result = moveUp(bv)) >= FINISHED) {
1097                                         updateLocal(bv, CURSOR, false);
1098                                         bv->unlockInset(this);
1099                                 }
1100                                 break;
1101                         case FINISHED_DOWN:
1102                                 if ((result = moveDown(bv)) >= FINISHED) {
1103                                         updateLocal(bv, CURSOR, false);
1104                                         bv->unlockInset(this);
1105                                 }
1106                                 break;
1107                         default:
1108                                 result = DISPATCHED;
1109                                 break;
1110                         }
1111                         the_locking_inset = 0;
1112 #ifdef WITH_WARNINGS
1113 #warning I changed this to always return Dispatched maybe it is wrong (20011001 Jug)
1114 #endif
1115                         return result;
1116                 }
1117         }
1118         hideInsetCursor(bv);
1119         bool clear = false;
1120         if (!lt) {
1121                 lt = getLyXText(bv);
1122                 clear = true;
1123         }
1124         int updwhat = 0;
1125         int updflag = false;
1126         switch (action) {
1127         // Normal chars
1128         case LFUN_SELFINSERT:
1129                 if (bv->buffer()->isReadonly()) {
1130 //          setErrorMessage(N_("Document is read only"));
1131                         break;
1132                 }
1133                 if (!arg.empty()) {
1134                         /* Automatically delete the currently selected
1135                          * text and replace it with what is being
1136                          * typed in now. Depends on lyxrc settings
1137                          * "auto_region_delete", which defaults to
1138                          * true (on). */
1139
1140                         setUndo(bv, Undo::INSERT,
1141                                 lt->cursor.par(), lt->cursor.par()->next());
1142                         bv->setState();
1143                         if (lyxrc.auto_region_delete) {
1144                                 if (lt->selection.set()) {
1145                                         lt->cutSelection(bv, false);
1146                                 }
1147                         }
1148                         lt->clearSelection();
1149                         for (string::size_type i = 0; i < arg.length(); ++i) {
1150                                 bv->owner()->getIntl()->getTrans().TranslateAndInsert(arg[i], lt);
1151                         }
1152                 }
1153                 lt->selection.cursor = lt->cursor;
1154                 updwhat = CURSOR_PAR;
1155                 updflag = true;
1156                 result = DISPATCHED_NOUPDATE;
1157                 break;
1158                 // --- Cursor Movements -----------------------------------
1159         case LFUN_RIGHTSEL:
1160                 finishUndo();
1161                 moveRight(bv, false, true);
1162                 lt->setSelection(bv);
1163                 updwhat = SELECTION;
1164                 break;
1165         case LFUN_RIGHT:
1166                 result = moveRight(bv);
1167                 finishUndo();
1168                 updwhat = CURSOR;
1169                 break;
1170         case LFUN_LEFTSEL:
1171                 finishUndo();
1172                 moveLeft(bv, false, true);
1173                 lt->setSelection(bv);
1174                 updwhat = SELECTION;
1175                 break;
1176         case LFUN_LEFT:
1177                 finishUndo();
1178                 result = moveLeft(bv);
1179                 updwhat = CURSOR;
1180                 break;
1181         case LFUN_DOWNSEL:
1182                 finishUndo();
1183                 moveDown(bv);
1184                 lt->setSelection(bv);
1185                 updwhat = SELECTION;
1186                 break;
1187         case LFUN_DOWN:
1188                 finishUndo();
1189                 result = moveDown(bv);
1190                 updwhat = CURSOR;
1191                 break;
1192         case LFUN_UPSEL:
1193                 finishUndo();
1194                 moveUp(bv);
1195                 lt->setSelection(bv);
1196                 updwhat = SELECTION;
1197                 break;
1198         case LFUN_UP:
1199                 finishUndo();
1200                 result = moveUp(bv);
1201                 updwhat = CURSOR;
1202                 break;
1203         case LFUN_HOME:
1204                 finishUndo();
1205                 lt->cursorHome(bv);
1206                 updwhat = CURSOR;
1207                 break;
1208         case LFUN_END:
1209                 lt->cursorEnd(bv);
1210                 updwhat = CURSOR;
1211                 break;
1212         case LFUN_BACKSPACE: {
1213                 setUndo(bv, Undo::DELETE,
1214                         lt->cursor.par(), lt->cursor.par()->next());
1215                 if (lt->selection.set())
1216                         lt->cutSelection(bv);
1217                 else
1218                         lt->backspace(bv);
1219                 updwhat = CURSOR_PAR;
1220                 updflag = true;
1221         }
1222         break;
1223         
1224         case LFUN_DELETE: {
1225                 setUndo(bv, Undo::DELETE,
1226                         lt->cursor.par(), lt->cursor.par()->next());
1227                 if (lt->selection.set()) {
1228                         lt->cutSelection(bv);
1229                 } else {
1230                         lt->Delete(bv);
1231                 }
1232                 updwhat = CURSOR_PAR;
1233                 updflag = true;
1234         }
1235         break;
1236         
1237         case LFUN_CUT: {
1238                 setUndo(bv, Undo::DELETE,
1239                         lt->cursor.par(), lt->cursor.par()->next());
1240                 lt->cutSelection(bv);
1241                 updwhat = CURSOR_PAR;
1242                 updflag = true;
1243         }
1244         break;
1245
1246         case LFUN_COPY:
1247                 finishUndo();
1248                 lt->copySelection(bv);
1249                 updwhat = CURSOR_PAR;
1250                 break;
1251         case LFUN_PASTESELECTION:
1252         {
1253                 string const clip(bv->getClipboard());
1254         
1255                 if (clip.empty())
1256                         break;
1257                 if (arg == "paragraph") {
1258                         lt->insertStringAsParagraphs(bv, clip);
1259                 } else {
1260                         lt->insertStringAsLines(bv, clip);
1261                 }
1262                 updwhat = CURSOR_PAR;
1263                 updflag = true;
1264                 break;
1265         }
1266         case LFUN_PASTE: {
1267                 if (!autoBreakRows) {
1268
1269                         if (CutAndPaste::nrOfParagraphs() > 1) {
1270                                 Alert::alert(_("Impossible operation"),
1271                                                    _("Cannot include more than one paragraph!"),
1272                                                    _("Sorry."));
1273                                 break;
1274                         }
1275                 }
1276                 setUndo(bv, Undo::INSERT,
1277                         lt->cursor.par(), lt->cursor.par()->next());
1278                 lt->pasteSelection(bv);
1279                 updwhat = CURSOR_PAR;
1280                 updflag = true;
1281         }
1282         break;
1283
1284         case LFUN_BREAKPARAGRAPH:
1285                 if (!autoBreakRows) {
1286                         result = DISPATCHED;
1287                         break;
1288                 }
1289                 lt->breakParagraph(bv, 0);
1290                 updwhat = FULL;
1291                 updflag = true;
1292                 break;
1293         case LFUN_BREAKPARAGRAPHKEEPLAYOUT:
1294                 if (!autoBreakRows) {
1295                         result = DISPATCHED;
1296                         break;
1297                 }
1298                 lt->breakParagraph(bv, 1);
1299                 updwhat = FULL;
1300                 updflag = true;
1301                 break;
1302
1303         case LFUN_BREAKLINE: {
1304                 if (!autoBreakRows) {
1305                         result = DISPATCHED;
1306                         break;
1307                 }
1308                 setUndo(bv, Undo::INSERT,
1309                         lt->cursor.par(), lt->cursor.par()->next());
1310                 lt->insertChar(bv, Paragraph::META_NEWLINE);
1311                 updwhat = CURSOR_PAR;
1312                 updflag = true;
1313         }
1314         break;
1315
1316         case LFUN_LAYOUT:
1317                 // do not set layouts on non breakable textinsets
1318                 if (autoBreakRows) {
1319                         layout_type cur_layout = cpar(bv)->layout;
1320           
1321                         // Derive layout number from given argument (string)
1322                         // and current buffer's textclass (number). */    
1323                         textclass_type tclass = bv->buffer()->params.textclass;
1324                         pair<bool, layout_type> layout = 
1325                                 textclasslist.NumberOfLayout(tclass, arg);
1326
1327                         // If the entry is obsolete, use the new one instead.
1328                         if (layout.first) {
1329                                 string obs = textclasslist.Style(tclass,layout.second).
1330                                         obsoleted_by();
1331                                 if (!obs.empty()) 
1332                                         layout = textclasslist.NumberOfLayout(tclass, obs);
1333                         }
1334
1335                         // see if we found the layout number:
1336                         if (!layout.first) {
1337                                 string const msg = string(N_("Layout ")) + arg + N_(" not known");
1338                                 bv->owner()->getLyXFunc()->dispatch(LFUN_MESSAGE, msg);
1339                                 break;
1340                         }
1341
1342                         if (cur_layout != layout.second) {
1343                                 cur_layout = layout.second;
1344                                 lt->setLayout(bv, layout.second);
1345                                 bv->owner()->setLayout(cpar(bv)->getLayout());
1346                                 updwhat = CURSOR_PAR;
1347                                 updflag = true;
1348                         }
1349                 } else {
1350                         // reset the layout box
1351                         bv->owner()->setLayout(cpar(bv)->getLayout());
1352                 }
1353                 break;
1354         case LFUN_PARAGRAPH_SPACING:
1355                 // This one is absolutely not working. When fiddling with this
1356                 // it also seems to me that the paragraphs inside the insettext
1357                 // inherit bufferparams/paragraphparams in a strange way. (Lgb)
1358         {
1359                 Paragraph * par = lt->cursor.par();
1360                 Spacing::Space cur_spacing = par->params().spacing().getSpace();
1361                 float cur_value = 1.0;
1362                 if (cur_spacing == Spacing::Other) {
1363                         cur_value = par->params().spacing().getValue();
1364                 }
1365                                 
1366                 istringstream istr(arg.c_str());
1367                 string tmp;
1368                 istr >> tmp;
1369                 Spacing::Space new_spacing = cur_spacing;
1370                 float new_value = cur_value;
1371                 if (tmp.empty()) {
1372                         lyxerr << "Missing argument to `paragraph-spacing'"
1373                                    << endl;
1374                 } else if (tmp == "single") {
1375                         new_spacing = Spacing::Single;
1376                 } else if (tmp == "onehalf") {
1377                         new_spacing = Spacing::Onehalf;
1378                 } else if (tmp == "double") {
1379                         new_spacing = Spacing::Double;
1380                 } else if (tmp == "other") {
1381                         new_spacing = Spacing::Other;
1382                         float tmpval = 0.0;
1383                         istr >> tmpval;
1384                         lyxerr << "new_value = " << tmpval << endl;
1385                         if (tmpval != 0.0)
1386                                 new_value = tmpval;
1387                 } else if (tmp == "default") {
1388                         new_spacing = Spacing::Default;
1389                 } else {
1390                         lyxerr << _("Unknown spacing argument: ")
1391                                    << arg << endl;
1392                 }
1393                 if (cur_spacing != new_spacing || cur_value != new_value) {
1394                         par->params().spacing(Spacing(new_spacing, new_value));
1395                         updwhat = CURSOR_PAR;
1396                         updflag = true;
1397                 }
1398         }
1399         break;
1400         
1401         default:
1402                 if (!bv->Dispatch(action, arg))
1403                         result = UNDISPATCHED;
1404                 break;
1405         }
1406
1407         if (clear)
1408                 lt = 0;
1409         if (updwhat > 0)
1410                 updateLocal(bv, updwhat, updflag);
1411         /// If the action has deleted all text in the inset, we need to change the
1412         // language to the language of the surronding text.
1413         if (!was_empty && par->size() == 0 && !par->next()) {
1414                 LyXFont font(LyXFont::ALL_IGNORE);
1415                 font.setLanguage(bv->getParentLanguage(this));
1416                 setFont(bv, font, false);
1417         }
1418
1419         if (result < FINISHED) {
1420                 showInsetCursor(bv);
1421         } else
1422                 bv->unlockInset(this);
1423         return result;
1424 }
1425
1426
1427 int InsetText::latex(Buffer const * buf, ostream & os, bool, bool) const
1428 {
1429         TexRow texrow;
1430         buf->latexParagraphs(os, par, 0, texrow);
1431         return texrow.rows();
1432 }
1433
1434
1435 int InsetText::ascii(Buffer const * buf, ostream & os, int linelen) const
1436 {
1437         Paragraph * p = par;
1438         unsigned int lines = 0;
1439         
1440         while (p) {
1441                 string const tmp = buf->asciiParagraph(p, linelen, p->previous()==0);
1442                 lines += lyx::count(tmp.begin(), tmp.end(), '\n');
1443                 os << tmp;
1444                 p = p->next();
1445         }
1446         return lines;
1447 }
1448
1449
1450 int InsetText::docbook(Buffer const * buf, ostream & os) const
1451 {
1452         Paragraph * p = par;
1453         unsigned int lines = 0;
1454
1455         vector<string> environment_stack(10);
1456         vector<string> environment_inner(10);
1457         
1458         int const command_depth = 0;
1459         string item_name;
1460         
1461         Paragraph::depth_type depth = 0; // paragraph depth
1462
1463         while (p) {
1464                 string sgmlparam;
1465                 int desc_on = 0; // description mode
1466
1467                 LyXLayout const & style =
1468                         textclasslist.Style(buf->params.textclass,
1469                                             p->layout);
1470
1471                 // environment tag closing
1472                 for (; depth > p->params().depth(); --depth) {
1473                         if (environment_inner[depth] != "!-- --") {
1474                                 item_name = "listitem";
1475                                 buf->sgmlCloseTag(os, command_depth + depth,
1476                                              item_name);
1477                                 if (environment_inner[depth] == "varlistentry")
1478                                         buf->sgmlCloseTag(os, depth+command_depth,
1479                                                      environment_inner[depth]);
1480                         }
1481                         buf->sgmlCloseTag(os, depth + command_depth,
1482                                      environment_stack[depth]);
1483                         environment_stack[depth].erase();
1484                         environment_inner[depth].erase();
1485                 }
1486
1487                 if (depth == p->params().depth()
1488                    && environment_stack[depth] != style.latexname()
1489                    && !environment_stack[depth].empty()) {
1490                         if (environment_inner[depth] != "!-- --") {
1491                                 item_name= "listitem";
1492                                 buf->sgmlCloseTag(os, command_depth+depth,
1493                                                   item_name);
1494                                 if (environment_inner[depth] == "varlistentry")
1495                                         buf->sgmlCloseTag(os,
1496                                                           depth + command_depth,
1497                                                           environment_inner[depth]);
1498                         }
1499                         
1500                         buf->sgmlCloseTag(os, depth + command_depth,
1501                                           environment_stack[depth]);
1502                         
1503                         environment_stack[depth].erase();
1504                         environment_inner[depth].erase();
1505                 }
1506
1507                 // Write opening SGML tags.
1508                 switch (style.latextype) {
1509                 case LATEX_PARAGRAPH:
1510                         buf->sgmlOpenTag(os, depth + command_depth,
1511                                          style.latexname());
1512                         break;
1513
1514                 case LATEX_COMMAND:
1515                         buf->sgmlError(p, 0,
1516                                        _("Error : LatexType Command not allowed here.\n"));
1517                         return -1;
1518                         break;
1519
1520                 case LATEX_ENVIRONMENT:
1521                 case LATEX_ITEM_ENVIRONMENT:
1522                         if (depth < p->params().depth()) {
1523                                 depth = p->params().depth();
1524                                 environment_stack[depth].erase();
1525                         }
1526
1527                         if (environment_stack[depth] != style.latexname()) {
1528                                 if (environment_stack.size() == depth + 1) {
1529                                         environment_stack.push_back("!-- --");
1530                                         environment_inner.push_back("!-- --");
1531                                 }
1532                                 environment_stack[depth] = style.latexname();
1533                                 environment_inner[depth] = "!-- --";
1534                                 buf->sgmlOpenTag(os, depth + command_depth,
1535                                                  environment_stack[depth]);
1536                         } else {
1537                                 if (environment_inner[depth] != "!-- --") {
1538                                         item_name= "listitem";
1539                                         buf->sgmlCloseTag(os,
1540                                                           command_depth + depth,
1541                                                           item_name);
1542                                         if (environment_inner[depth] == "varlistentry")
1543                                                 buf->sgmlCloseTag(os,
1544                                                                   depth + command_depth,
1545                                                                   environment_inner[depth]);
1546                                 }
1547                         }
1548                         
1549                         if (style.latextype == LATEX_ENVIRONMENT) {
1550                                 if (!style.latexparam().empty()) {
1551                                         if (style.latexparam() == "CDATA")
1552                                                 os << "<![CDATA[";
1553                                         else
1554                                                 buf->sgmlOpenTag(os, depth + command_depth,
1555                                                                  style.latexparam());
1556                                 }
1557                                 break;
1558                         }
1559
1560                         desc_on = (style.labeltype == LABEL_MANUAL);
1561
1562                         if (desc_on)
1563                                 environment_inner[depth]= "varlistentry";
1564                         else
1565                                 environment_inner[depth]= "listitem";
1566
1567                         buf->sgmlOpenTag(os, depth + 1 + command_depth,
1568                                          environment_inner[depth]);
1569
1570                         if (desc_on) {
1571                                 item_name= "term";
1572                                 buf->sgmlOpenTag(os, depth + 1 + command_depth,
1573                                                  item_name);
1574                         } else {
1575                                 item_name= "para";
1576                                 buf->sgmlOpenTag(os, depth + 1 + command_depth,
1577                                                  item_name);
1578                         }
1579                         break;
1580                 default:
1581                         buf->sgmlOpenTag(os, depth + command_depth,
1582                                          style.latexname());
1583                         break;
1584                 }
1585
1586                 buf->simpleDocBookOnePar(os, p, desc_on,
1587                                          depth + 1 + command_depth);
1588                 p = p->next();
1589
1590                 string end_tag;
1591                 // write closing SGML tags
1592                 switch (style.latextype) {
1593                 case LATEX_ENVIRONMENT:
1594                         if (!style.latexparam().empty()) {
1595                                 if (style.latexparam() == "CDATA")
1596                                         os << "]]>";
1597                                 else
1598                                         buf->sgmlCloseTag(os, depth + command_depth,
1599                                                           style.latexparam());
1600                         }
1601                         break;
1602                 case LATEX_ITEM_ENVIRONMENT:
1603                         if (desc_on == 1) break;
1604                         end_tag= "para";
1605                         buf->sgmlCloseTag(os, depth + 1 + command_depth, end_tag);
1606                         break;
1607                 case LATEX_PARAGRAPH:
1608                         buf->sgmlCloseTag(os, depth + command_depth, style.latexname());
1609                         break;
1610                 default:
1611                         buf->sgmlCloseTag(os, depth + command_depth, style.latexname());
1612                         break;
1613                 }
1614         }
1615
1616         // Close open tags
1617         for (int d = depth; d >= 0; --d) {
1618                 if (!environment_stack[depth].empty()) {
1619                         if (environment_inner[depth] != "!-- --") {
1620                                 item_name = "listitem";
1621                                 buf->sgmlCloseTag(os, command_depth + depth,
1622                                                   item_name);
1623                                if (environment_inner[depth] == "varlistentry")
1624                                        buf->sgmlCloseTag(os, depth + command_depth,
1625                                                          environment_inner[depth]);
1626                         }
1627                         
1628                         buf->sgmlCloseTag(os, depth + command_depth,
1629                                           environment_stack[depth]);
1630                 }
1631         }
1632         
1633         return lines;
1634 }
1635
1636
1637 void InsetText::validate(LaTeXFeatures & features) const
1638 {
1639         Paragraph * p = par;
1640         while (p) {
1641                 p->validate(features);
1642                 p = p->next();
1643         }
1644 }
1645
1646
1647 int InsetText::beginningOfMainBody(Buffer const * buf, Paragraph * p) const
1648 {
1649         if (textclasslist.Style(buf->params.textclass,
1650                                 p->getLayout()).labeltype != LABEL_MANUAL)
1651                 return 0;
1652         else
1653                 return p->beginningOfMainBody();
1654 }
1655
1656
1657 void InsetText::getCursorPos(BufferView * bv,
1658                              int & x, int & y) const
1659 {
1660         if (the_locking_inset) {
1661                 the_locking_inset->getCursorPos(bv, x, y);
1662                 return;
1663         }
1664         x = cx(bv);
1665         y = cy(bv);
1666 }
1667
1668
1669 unsigned int InsetText::insetInInsetY()
1670 {
1671         if (!the_locking_inset)
1672                 return 0;
1673
1674         return (inset_y + the_locking_inset->insetInInsetY());
1675 }
1676
1677
1678 void InsetText::toggleInsetCursor(BufferView * bv)
1679 {
1680         if (the_locking_inset) {
1681                 the_locking_inset->toggleInsetCursor(bv);
1682                 return;
1683         }
1684
1685         LyXFont const font(getLyXText(bv)->getFont(bv->buffer(), cpar(bv), cpos(bv)));
1686
1687         int const asc = lyxfont::maxAscent(font);
1688         int const desc = lyxfont::maxDescent(font);
1689   
1690         if (isCursorVisible())
1691                 bv->hideLockedInsetCursor();
1692         else
1693                 bv->showLockedInsetCursor(cx(bv), cy(bv), asc, desc);
1694         toggleCursorVisible();
1695 }
1696
1697
1698 void InsetText::showInsetCursor(BufferView * bv, bool show)
1699 {
1700         if (the_locking_inset) {
1701                 the_locking_inset->showInsetCursor(bv, show);
1702                 return;
1703         }
1704         if (!isCursorVisible()) {
1705                 LyXFont const font =
1706                         getLyXText(bv)->getFont(bv->buffer(), cpar(bv), cpos(bv));
1707         
1708                 int const asc = lyxfont::maxAscent(font);
1709                 int const desc = lyxfont::maxDescent(font);
1710
1711                 bv->fitLockedInsetCursor(cx(bv), cy(bv), asc, desc);
1712                 if (show)
1713                         bv->showLockedInsetCursor(cx(bv), cy(bv), asc, desc);
1714                 setCursorVisible(true);
1715         }
1716 }
1717
1718
1719 void InsetText::hideInsetCursor(BufferView * bv)
1720 {
1721         if (isCursorVisible()) {
1722                 bv->hideLockedInsetCursor();
1723                 setCursorVisible(false);
1724         }
1725         if (the_locking_inset)
1726                 the_locking_inset->hideInsetCursor(bv);
1727 }
1728
1729
1730 void InsetText::fitInsetCursor(BufferView * bv) const
1731 {
1732         if (the_locking_inset) {
1733                 the_locking_inset->fitInsetCursor(bv);
1734                 return;
1735         }
1736         LyXFont const font =
1737                 getLyXText(bv)->getFont(bv->buffer(), cpar(bv), cpos(bv));
1738         
1739         int const asc = lyxfont::maxAscent(font);
1740         int const desc = lyxfont::maxDescent(font);
1741
1742         bv->fitLockedInsetCursor(cx(bv), cy(bv), asc, desc);
1743 }
1744
1745
1746 UpdatableInset::RESULT
1747 InsetText::moveRight(BufferView * bv, bool activate_inset, bool selecting)
1748 {
1749         if (getLyXText(bv)->cursor.par()->isRightToLeftPar(bv->buffer()->params))
1750                 return moveLeftIntern(bv, false, activate_inset, selecting);
1751         else
1752                 return moveRightIntern(bv, false, activate_inset, selecting);
1753 }
1754
1755
1756 UpdatableInset::RESULT
1757 InsetText::moveLeft(BufferView * bv, bool activate_inset, bool selecting)
1758 {
1759         if (getLyXText(bv)->cursor.par()->isRightToLeftPar(bv->buffer()->params))
1760                 return moveRightIntern(bv, true, activate_inset, selecting);
1761         else
1762                 return moveLeftIntern(bv, true, activate_inset, selecting);
1763 }
1764
1765
1766 UpdatableInset::RESULT
1767 InsetText::moveRightIntern(BufferView * bv, bool behind, 
1768                            bool activate_inset, bool selecting)
1769 {
1770         if (!cpar(bv)->next() && (cpos(bv) >= cpar(bv)->size()))
1771                 return FINISHED_RIGHT;
1772         if (activate_inset && checkAndActivateInset(bv, behind))
1773                 return DISPATCHED;
1774         getLyXText(bv)->cursorRight(bv);
1775         if (!selecting)
1776                 getLyXText(bv)->selection.cursor = getLyXText(bv)->cursor;
1777         return DISPATCHED_NOUPDATE;
1778 }
1779
1780
1781 UpdatableInset::RESULT
1782 InsetText::moveLeftIntern(BufferView * bv, bool behind,
1783                           bool activate_inset, bool selecting)
1784 {
1785         if (!cpar(bv)->previous() && (cpos(bv) <= 0))
1786                 return FINISHED;
1787         getLyXText(bv)->cursorLeft(bv);
1788         if (!selecting)
1789                 getLyXText(bv)->selection.cursor = getLyXText(bv)->cursor;
1790         if (activate_inset && checkAndActivateInset(bv, behind))
1791                 return DISPATCHED;
1792         return DISPATCHED_NOUPDATE;
1793 }
1794
1795
1796 UpdatableInset::RESULT
1797 InsetText::moveUp(BufferView * bv)
1798 {
1799         if (!crow(bv)->previous())
1800                 return FINISHED_UP;
1801         getLyXText(bv)->cursorUp(bv);
1802         return DISPATCHED_NOUPDATE;
1803 }
1804
1805
1806 UpdatableInset::RESULT
1807 InsetText::moveDown(BufferView * bv)
1808 {
1809         if (!crow(bv)->next())
1810                 return FINISHED_DOWN;
1811         getLyXText(bv)->cursorDown(bv);
1812         return DISPATCHED_NOUPDATE;
1813 }
1814
1815
1816 bool InsetText::insertInset(BufferView * bv, Inset * inset)
1817 {
1818         if (the_locking_inset) {
1819                 if (the_locking_inset->insetAllowed(inset))
1820                         return the_locking_inset->insertInset(bv, inset);
1821                 return false;
1822         }
1823         bool clear = false;
1824         if (!lt) {
1825                 lt = getLyXText(bv);
1826                 clear = true;
1827         }
1828         setUndo(bv, Undo::FINISH, lt->cursor.par(), lt->cursor.par()->next());
1829         freezeUndo();
1830         inset->setOwner(this);
1831         hideInsetCursor(bv);
1832         lt->insertInset(bv, inset);
1833         bv->fitCursor();
1834         if (clear)
1835                 lt = 0;
1836         updateLocal(bv, CURSOR_PAR|CURSOR, true);
1837         unFreezeUndo();
1838         return true;
1839 }
1840
1841
1842 bool InsetText::insetAllowed(Inset::Code code) const
1843 {
1844         // in_insetAllowed is a really gross hack,
1845         // to allow us to call the owner's insetAllowed
1846         // without stack overflow, which can happen
1847         // when the owner uses InsetCollapsable::insetAllowed()
1848         bool ret = true;
1849         if (in_insetAllowed)
1850                 return ret;
1851         in_insetAllowed = true;
1852         if (the_locking_inset)
1853                 ret = the_locking_inset->insetAllowed(code);
1854         else if (owner())
1855                 ret = owner()->insetAllowed(code);
1856         in_insetAllowed = false;
1857         return ret;
1858 }
1859
1860
1861 UpdatableInset * InsetText::getLockingInset() const
1862 {
1863         return the_locking_inset ? the_locking_inset->getLockingInset() :
1864                 const_cast<InsetText *>(this);
1865 }
1866
1867
1868 UpdatableInset * InsetText::getFirstLockingInsetOfType(Inset::Code c)
1869 {
1870         if (c == lyxCode())
1871                 return this;
1872         if (the_locking_inset)
1873                 return the_locking_inset->getFirstLockingInsetOfType(c);
1874         return 0;
1875 }
1876
1877
1878 bool InsetText::showInsetDialog(BufferView * bv) const
1879 {
1880         if (the_locking_inset)
1881                 return the_locking_inset->showInsetDialog(bv);
1882         return false;
1883 }
1884
1885
1886 vector<string> const InsetText::getLabelList() const 
1887 {
1888         vector<string> label_list;
1889
1890         Paragraph * tpar = par;
1891         while (tpar) {
1892                 Paragraph::inset_iterator beg = tpar->inset_iterator_begin();
1893                 Paragraph::inset_iterator end = tpar->inset_iterator_end();
1894                 for (; beg != end; ++beg) {
1895                         vector<string> const l = (*beg)->getLabelList();
1896                         label_list.insert(label_list.end(), l.begin(), l.end());
1897                 }
1898                 tpar = tpar->next();
1899         }
1900         return label_list;
1901 }
1902
1903
1904 void InsetText::setFont(BufferView * bv, LyXFont const & font, bool toggleall,
1905                         bool selectall)
1906 {
1907         if (the_locking_inset) {
1908                 the_locking_inset->setFont(bv, font, toggleall, selectall);
1909                 return;
1910         }
1911         if ((!par->next() && !par->size()) || !cpar(bv)->size()) {
1912                 getLyXText(bv)->setFont(bv, font, toggleall);
1913                 return;
1914         }
1915         bool clear = false;
1916         if (!lt) {
1917                 lt = getLyXText(bv);
1918                 clear = true;
1919         }
1920         if (lt->selection.set()) {
1921                 setUndo(bv, Undo::EDIT, lt->cursor.par(), lt->cursor.par()->next());
1922         }
1923         if (selectall)
1924                 selectAll(bv);
1925         lt->toggleFree(bv, font, toggleall);
1926         if (selectall)
1927                 lt->clearSelection();
1928         bv->fitCursor();
1929         bool flag = (selectall || lt->selection.set());
1930         if (clear)
1931                 lt = 0;
1932         if (flag)
1933                 updateLocal(bv, FULL, true);
1934         else
1935                 updateLocal(bv, CURSOR_PAR, true);
1936 }
1937
1938
1939 bool InsetText::checkAndActivateInset(BufferView * bv, bool behind)
1940 {
1941         if (cpar(bv)->isInset(cpos(bv))) {
1942                 unsigned int x;
1943                 unsigned int y;
1944                 Inset * inset =
1945                         static_cast<UpdatableInset*>(cpar(bv)->getInset(cpos(bv)));
1946                 if (!isHighlyEditableInset(inset))
1947                         return false;
1948                 LyXFont const font =
1949                         getLyXText(bv)->getFont(bv->buffer(), cpar(bv), cpos(bv));
1950                 if (behind) {
1951                         x = inset->width(bv, font);
1952                         y = font.isRightToLeft() ? 0 : inset->descent(bv, font);
1953                 } else {
1954                         x = 0;
1955                         y = font.isRightToLeft() ? inset->descent(bv, font) : 0;
1956                 }
1957                 //inset_x = cx(bv) - top_x + drawTextXOffset;
1958                 //inset_y = cy(bv) + drawTextYOffset;
1959                 inset->edit(bv, x, y, 0);
1960                 if (!the_locking_inset)
1961                         return false;
1962                 updateLocal(bv, CURSOR, false);
1963                 return true;
1964         }
1965         return false;
1966 }
1967
1968
1969 bool InsetText::checkAndActivateInset(BufferView * bv, int x, int y,
1970                                       int button)
1971 {
1972         x -= drawTextXOffset;
1973         int dummyx = x;
1974         int dummyy = y + insetAscent;
1975         Inset * inset = bv->checkInsetHit(getLyXText(bv), dummyx, dummyy);
1976
1977         if (inset) {
1978                 if (x < 0)
1979                         x = insetWidth;
1980                 if (y < 0)
1981                         y = insetDescent;
1982                 inset_x = cx(bv) - top_x + drawTextXOffset;
1983                 inset_y = cy(bv) + drawTextYOffset;
1984                 inset->edit(bv, x - inset_x, y - inset_y, button);
1985                 if (!the_locking_inset)
1986                         return false;
1987                 updateLocal(bv, CURSOR, false);
1988                 return true;
1989         }
1990         return false;
1991 }
1992
1993
1994 int InsetText::getMaxWidth(BufferView * bv, UpdatableInset const * inset) const
1995 {
1996 #if 0
1997         int w = UpdatableInset::getMaxWidth(bv, inset);
1998         if (w < 0) {
1999                 return -1;
2000         }
2001         if (owner()) {
2002                 w = w - top_x + owner()->x();
2003                 return w;
2004         }
2005         w -= (2 * TEXT_TO_INSET_OFFSET);
2006         return w - top_x;
2007 #else
2008         return UpdatableInset::getMaxWidth(bv, inset);
2009 #endif
2010 }
2011
2012
2013 void InsetText::setParagraphData(Paragraph * p, bool same_id)
2014 {
2015         // we have to unlock any locked inset otherwise we're in troubles
2016         the_locking_inset = 0;
2017         while (par) {
2018                 Paragraph * tmp = par->next();
2019                 delete par;
2020                 par = tmp;
2021         }
2022
2023         par = new Paragraph(*p, same_id);
2024         par->setInsetOwner(this);
2025         Paragraph * np = par;
2026         while (p->next()) {
2027                 p = p->next();
2028                 np->next(new Paragraph(*p, same_id));
2029                 np->next()->previous(np);
2030                 np = np->next();
2031                 np->setInsetOwner(this);
2032         }
2033         reinitLyXText();
2034         need_update = INIT;
2035 }
2036
2037
2038 void InsetText::setText(string const & data)
2039 {
2040         clear();
2041         LyXFont font(LyXFont::ALL_SANE);
2042         for (unsigned int i=0; i < data.length(); ++i)
2043                 par->insertChar(i, data[i], font);
2044 }
2045
2046
2047 void InsetText::setAutoBreakRows(bool flag)
2048 {
2049         if (flag != autoBreakRows) {
2050                 autoBreakRows = flag;
2051                 if (!flag)
2052                         removeNewlines();
2053                 need_update = INIT;
2054         }
2055 }
2056
2057
2058 void InsetText::setDrawFrame(BufferView * bv, DrawFrame how)
2059 {
2060         if (how != drawFrame_) {
2061                 drawFrame_ = how;
2062                 if (bv)
2063                         updateLocal(bv, DRAW_FRAME, false);
2064         }
2065 }
2066
2067
2068 void InsetText::setFrameColor(BufferView * bv, LColor::color col)
2069 {
2070         if (frame_color != col) {
2071                 frame_color = col;
2072                 if (bv)
2073                         updateLocal(bv, DRAW_FRAME, false);
2074         }
2075 }
2076
2077
2078 int InsetText::cx(BufferView * bv) const
2079 {
2080         // we do nothing dangerous so we use a local cache
2081         LyXText * llt = getLyXText(bv);
2082         int x = llt->cursor.x() + top_x + TEXT_TO_INSET_OFFSET;
2083         if (the_locking_inset) {
2084                 LyXFont font = llt->getFont(bv->buffer(), llt->cursor.par(),
2085                                             llt->cursor.pos());
2086                 if (font.isVisibleRightToLeft())
2087                         x -= the_locking_inset->width(bv, font);
2088         }
2089         return x;
2090 }
2091
2092
2093 int InsetText::cy(BufferView * bv) const
2094 {
2095         LyXFont font;
2096         return getLyXText(bv)->cursor.y() - ascent(bv, font) + TEXT_TO_INSET_OFFSET;
2097 }
2098
2099
2100 pos_type InsetText::cpos(BufferView * bv) const
2101 {
2102         return getLyXText(bv)->cursor.pos();
2103 }
2104
2105
2106 Paragraph * InsetText::cpar(BufferView * bv) const
2107 {
2108         return getLyXText(bv)->cursor.par();
2109 }
2110
2111
2112 bool InsetText::cboundary(BufferView * bv) const
2113 {
2114         return getLyXText(bv)->cursor.boundary();
2115 }
2116
2117
2118 Row * InsetText::crow(BufferView * bv) const
2119 {
2120         return getLyXText(bv)->cursor.row();
2121 }
2122
2123
2124 LyXText * InsetText::getLyXText(BufferView const * lbv,
2125                                 bool const recursive) const
2126 {
2127         if (!recursive && (cached_bview == lbv)) {
2128                 LyXText * lt = cached_text.get();
2129                 lyx::Assert(lt && lt->firstRow()->par() == par);
2130                 return lt;
2131         }
2132         
2133         // Super UGLY! (Lgb)
2134         BufferView * bv = const_cast<BufferView *>(lbv);
2135         
2136         cached_bview = bv;
2137         Cache::iterator it = cache.find(bv);
2138
2139         if (it != cache.end()) {
2140                 if (do_reinit) {
2141                         reinitLyXText();
2142                 } else if (do_resize) {
2143                         resizeLyXText(do_resize);
2144                 } else {
2145                         if (lt || !it->second.remove) {
2146                                 lyx::Assert(it->second.text.get());
2147                                 cached_text = it->second.text;
2148                                 if (recursive && the_locking_inset) {
2149                                         return the_locking_inset->getLyXText(bv, true);
2150                                 }
2151                                 return cached_text.get();
2152                         } else if (it->second.remove) {
2153                                 if (locked) {
2154                                         saveLyXTextState(it->second.text.get());
2155                                 } else {
2156                                         sstate.lpar = 0;
2157                                 }
2158                         }
2159                         //
2160                         // when we have to reinit the existing LyXText!
2161                         //
2162                         it->second.text->init(bv);
2163                         restoreLyXTextState(bv, it->second.text.get());
2164                         it->second.remove = false;
2165                 }
2166                 cached_text = it->second.text;
2167                 if (the_locking_inset && recursive) {
2168                         return the_locking_inset->getLyXText(bv);
2169                 }
2170                 return cached_text.get();
2171         }
2172         ///
2173         // we are here only if we don't have a BufferView * in the cache!!!
2174         ///
2175         cached_text.reset(new LyXText(const_cast<InsetText *>(this)));
2176         cached_text->init(bv);
2177         restoreLyXTextState(bv, cached_text.get());
2178
2179         cache.insert(make_pair(bv, cached_text));
2180         
2181         if (the_locking_inset && recursive) {
2182                 return the_locking_inset->getLyXText(bv);
2183         }
2184         return cached_text.get();
2185 }
2186
2187
2188 void InsetText::deleteLyXText(BufferView * bv, bool recursive) const
2189 {
2190         cached_bview = 0;
2191
2192         Cache::iterator it = cache.find(bv);
2193         
2194         if (it == cache.end()) {
2195                 return;
2196         }
2197
2198         lyx::Assert(it->second.text.get());
2199
2200         it->second.remove = true;
2201         if (recursive) {
2202                 /// then remove all LyXText in text-insets
2203                 Paragraph * p = par;
2204                 for (; p; p = p->next()) {
2205                         p->deleteInsetsLyXText(bv);
2206                 }
2207         }
2208 }
2209
2210
2211 void InsetText::resizeLyXText(BufferView * bv, bool force) const
2212 {
2213         if (lt) {
2214                 // we cannot resize this because we are in use!
2215                 // so do this on the next possible getLyXText()
2216                 do_resize = bv;
2217                 return;
2218         }
2219         do_resize = 0;
2220 //      lyxerr << "InsetText::resizeLyXText\n";
2221         if (!par->next() && !par->size()) { // no data, resize not neccessary!
2222                 // we have to do this as a fixed width may have changed!
2223                 LyXText * t = getLyXText(bv);
2224                 saveLyXTextState(t);
2225                 t->init(bv, true);
2226                 restoreLyXTextState(bv, t);
2227                 return;
2228         }
2229         // one endless line, resize normally not necessary
2230         if (!force && getMaxWidth(bv, this) < 0)
2231                 return;
2232
2233         Cache::iterator it = cache.find(bv);
2234         if (it == cache.end()) {
2235                 return;
2236         }
2237         lyx::Assert(it->second.text.get());
2238
2239         LyXText * t = it->second.text.get();
2240         saveLyXTextState(t);
2241         for (Paragraph * p = par; p; p = p->next()) {
2242                 p->resizeInsetsLyXText(bv);
2243         }
2244         t->init(bv, true);
2245         restoreLyXTextState(bv, t);
2246         if (the_locking_inset) {
2247                 inset_x = cx(bv) - top_x + drawTextXOffset;
2248                 inset_y = cy(bv) + drawTextYOffset;
2249         }
2250
2251         if (bv->screen()) {
2252                 t->first = bv->screen()->topCursorVisible(t);
2253         }
2254         if (!owner()) {
2255                 updateLocal(bv, FULL, false);
2256                 // this will scroll the screen such that the cursor becomes visible 
2257                 bv->updateScrollbar();
2258         } else {
2259                 need_update |= FULL;
2260         }
2261 }
2262
2263
2264 void InsetText::reinitLyXText() const
2265 {
2266         if (lt) {
2267                 // we cannot resize this because we are in use!
2268                 // so do this on the next possible getLyXText()
2269                 do_reinit = true;
2270                 return;
2271         }
2272         do_reinit = false;
2273         do_resize = 0;
2274 //      lyxerr << "InsetText::reinitLyXText\n";
2275         for(Cache::iterator it = cache.begin(); it != cache.end(); ++it) {
2276                 lyx::Assert(it->second.text.get());
2277
2278                 LyXText * t = it->second.text.get();
2279                 BufferView * bv = it->first;
2280
2281                 saveLyXTextState(t);
2282                 for (Paragraph * p = par; p; p = p->next()) {
2283                         p->resizeInsetsLyXText(bv);
2284                 }
2285                 t->init(bv, true);
2286                 restoreLyXTextState(bv, t);
2287                 if (the_locking_inset) {
2288                         inset_x = cx(bv) - top_x + drawTextXOffset;
2289                         inset_y = cy(bv) + drawTextYOffset;
2290                 }
2291                 if (bv->screen()) {
2292                         t->first = bv->screen()->topCursorVisible(t);
2293                 }
2294                 if (!owner()) {
2295                         updateLocal(bv, FULL, false);
2296                         // this will scroll the screen such that the cursor becomes visible 
2297                         bv->updateScrollbar();
2298                 } else {
2299                         need_update = FULL;
2300                 }
2301         }
2302 }
2303
2304
2305 void InsetText::removeNewlines()
2306 {
2307         bool changed = false;
2308         
2309         for (Paragraph * p = par; p; p = p->next()) {
2310                 for (int i = 0; i < p->size(); ++i) {
2311                         if (p->getChar(i) == Paragraph::META_NEWLINE) {
2312                                 changed = true;
2313                                 p->erase(i);
2314                         }
2315                 }
2316         }
2317         if (changed)
2318                 reinitLyXText();
2319 }
2320
2321
2322 bool InsetText::nodraw() const
2323 {
2324         if (the_locking_inset)
2325                 return the_locking_inset->nodraw();
2326         return UpdatableInset::nodraw();
2327 }
2328
2329
2330 int InsetText::scroll(bool recursive) const
2331 {
2332         int sx = UpdatableInset::scroll(false);
2333
2334         if (recursive && the_locking_inset)
2335                 sx += the_locking_inset->scroll(recursive);
2336
2337         return sx;
2338 }
2339
2340
2341 bool InsetText::doClearArea() const
2342 {
2343         return !locked || (need_update & (FULL|INIT));
2344 }
2345
2346
2347 void InsetText::selectAll(BufferView * bv)
2348 {
2349         getLyXText(bv)->cursorTop(bv);
2350         getLyXText(bv)->selection.cursor = getLyXText(bv)->cursor;
2351         getLyXText(bv)->cursorBottom(bv);
2352         getLyXText(bv)->setSelection(bv);
2353 }
2354
2355
2356 void InsetText::clearSelection(BufferView * bv)
2357 {
2358         getLyXText(bv)->clearSelection();
2359 }
2360
2361
2362 void InsetText::clearInset(BufferView * bv, int baseline, bool & cleared) const
2363 {
2364         Painter & pain = bv->painter();
2365         int w = insetWidth;
2366         int h = insetAscent + insetDescent;
2367         int ty = baseline - insetAscent;
2368         
2369         if (ty < 0) {
2370                 h += ty;
2371                 ty = 0;
2372         }
2373         if ((ty + h) > pain.paperHeight())
2374                 h = pain.paperHeight();
2375         if ((top_x + drawTextXOffset + w) > pain.paperWidth())
2376                 w = pain.paperWidth();
2377 //      w -= TEXT_TO_INSET_OFFSET;
2378         pain.fillRectangle(top_x, ty, w+1, h+1, backgroundColor());
2379         cleared = true;
2380         need_update = FULL;
2381         frame_is_visible = false;
2382 }
2383
2384
2385 Paragraph * InsetText::getParFromID(int id) const
2386 {
2387 #if 0
2388         Paragraph * result = par;
2389         Paragraph * ires = 0;
2390         while (result && result->id() != id) {
2391                 if ((ires = result->getParFromID(id)))
2392                         return ires;
2393                 result = result->next();
2394         }
2395         return result;
2396 #else
2397         Paragraph * tmp = par;
2398         while (tmp) {
2399                 if (tmp->id() == id) {
2400                         return tmp;
2401                 }
2402                 Paragraph * tmp2 = tmp->getParFromID(id);
2403                 if (tmp2 != 0) {
2404                         return tmp2;
2405                 }
2406                 tmp = tmp->next();
2407         }
2408         return 0;
2409 #endif
2410 }
2411
2412
2413 Paragraph * InsetText::firstParagraph() const
2414 {
2415         Paragraph * result;
2416         if (the_locking_inset)
2417                 if ((result = the_locking_inset->firstParagraph()))
2418                         return result;
2419         return par;
2420 }
2421
2422
2423 Paragraph * InsetText::getFirstParagraph(int i) const
2424 {
2425         return (i == 0) ? par : 0;
2426 }
2427
2428
2429 LyXCursor const & InsetText::cursor(BufferView * bv) const
2430 {
2431                 if (the_locking_inset)
2432                                 return the_locking_inset->cursor(bv);
2433                 return getLyXText(bv)->cursor;
2434 }
2435
2436
2437 Paragraph * InsetText::paragraph() const
2438 {
2439         return par;
2440 }
2441
2442
2443 void InsetText::paragraph(Paragraph * p)
2444 {
2445         // GENERAL COMMENT: We don't have to free the old paragraphs as the
2446         // caller of this function has to take care of it. This IS important
2447         // as we could have to insert a paragraph before this one and just
2448         // link the actual to a new ones next and set it with this function
2449         // and are done!
2450         par = p;
2451         // set ourself as owner for all the paragraphs inserted!
2452         Paragraph * np = par;
2453         while (np) {
2454                 np->setInsetOwner(this);
2455                 np = np->next();
2456         }
2457         reinitLyXText();
2458         // redraw myself when asked for
2459         need_update = INIT;
2460 }
2461
2462
2463 Inset * InsetText::getInsetFromID(int id_arg) const
2464 {
2465         if (id_arg == id())
2466                 return const_cast<InsetText *>(this);
2467
2468         Paragraph * lp = par;
2469
2470         while (lp) {
2471                 for (Paragraph::inset_iterator it = lp->inset_iterator_begin(),
2472                          en = lp->inset_iterator_end();
2473                          it != en; ++it)
2474                 {
2475                         if ((*it)->id() == id_arg)
2476                                 return *it;
2477                         Inset * in = (*it)->getInsetFromID(id_arg);
2478                         if (in)
2479                                 return in;
2480                 }
2481                 lp = lp->next();
2482         }
2483         return 0;
2484 }
2485
2486
2487 string const InsetText::selectNextWordToSpellcheck(BufferView * bv, float & value) const
2488 {
2489         bool clear = false;
2490         string str;
2491
2492         if (!lt) {
2493                 lt = getLyXText(bv);
2494                 clear = true;
2495         }
2496         if (the_locking_inset) {
2497                 str = the_locking_inset->selectNextWordToSpellcheck(bv, value);
2498                 if (!str.empty()) {
2499                         value += cy(bv);
2500                         if (clear)
2501                                 lt = 0;
2502                         return str;
2503                 }
2504                 // we have to go on checking so move cusor to the next char
2505                 lt->cursor.pos(lt->cursor.pos() + 1);
2506         }
2507         str = lt->selectNextWordToSpellcheck(bv, value);
2508         if (str.empty())
2509                 bv->unlockInset(const_cast<InsetText *>(this));
2510         else
2511                 value = cy(bv);
2512         if (clear)
2513                 lt = 0;
2514         return str;
2515 }
2516
2517
2518 void InsetText::selectSelectedWord(BufferView * bv)
2519 {
2520         if (the_locking_inset) {
2521                 the_locking_inset->selectSelectedWord(bv);
2522                 return;
2523         }
2524         getLyXText(bv)->selectSelectedWord(bv);
2525         updateLocal(bv, SELECTION, false);
2526 }
2527
2528
2529 void InsetText::toggleSelection(BufferView * bv, bool kill_selection)
2530 {
2531         if (the_locking_inset) {
2532                 the_locking_inset->toggleSelection(bv, kill_selection);
2533         }
2534         bool clear = false;
2535         if (!lt) {
2536                 lt = getLyXText(bv);
2537                 clear = true;
2538         }
2539
2540         int x = top_x + TEXT_TO_INSET_OFFSET;
2541
2542         Row * row = lt->firstRow();
2543         int y_offset = top_baseline - row->ascent_of_text();
2544         int y = y_offset;
2545         while ((row != 0) && ((y+row->height()) <= 0)) {
2546                 y += row->height();
2547                 row = row->next();
2548         }
2549         if (y_offset < 0)
2550                 y_offset = y;
2551         
2552         if (need_update & SELECTION)
2553                 need_update = NONE;
2554         bv->screen()->toggleSelection(lt, bv, kill_selection, y_offset, x);
2555         if (clear)
2556                 lt = 0;
2557 }
2558
2559
2560 bool InsetText::searchForward(BufferView * bv, string const & str,
2561                               bool cs, bool mw)
2562 {
2563         if (the_locking_inset) {
2564                 if (the_locking_inset->searchForward(bv, str, cs, mw))
2565                         return true;
2566                 bool clear = false;
2567                 if (!lt) {
2568                         lt = getLyXText(bv);
2569                         clear = true;
2570                 }
2571                 Paragraph * lpar = lt->cursor.par();
2572                 pos_type pos = lt->cursor.pos();
2573                 if (pos < lpar->size() - 1)
2574                         ++pos;
2575                 else {
2576                         pos = 0;
2577                         lpar = lpar->next();
2578                 }
2579                 if (!lpar) {
2580                         if (clear)
2581                                 lt = 0;
2582                         // we have to unlock ourself in this function by default!
2583                         bv->unlockInset(const_cast<InsetText *>(this));
2584                         return false;
2585                 }
2586                 lt->setCursor(bv, lpar, pos);
2587                 if (clear)
2588                         lt = 0;
2589         }
2590         if (LyXFind(bv, str, true, true, cs , mw)) {
2591                 return true;
2592         }
2593         // we have to unlock ourself in this function by default!
2594         bv->unlockInset(const_cast<InsetText *>(this));
2595         return false;
2596 }
2597
2598 bool InsetText::searchBackward(BufferView * bv, string const & str,
2599                                bool cs, bool mw)
2600 {
2601         if (the_locking_inset)
2602                 if (the_locking_inset->searchBackward(bv, str, cs, mw))
2603                         return true;
2604         if (LyXFind(bv, str, false, true, cs, mw)) {
2605                 return true;
2606         }
2607         // we have to unlock ourself in this function by default!
2608         bv->unlockInset(const_cast<InsetText *>(this));
2609         return false;
2610 }
2611
2612
2613 bool InsetText::checkInsertChar(LyXFont & font)
2614 {
2615         if (owner())
2616                 return owner()->checkInsertChar(font);
2617         return true;
2618 }
2619
2620
2621 void InsetText::collapseParagraphs(BufferParams const & bparams) const
2622 {
2623         while(par->next()) {
2624                 if (!par->isSeparator(par->size()-1))
2625                         par->insertChar(par->size()-1, ' ');
2626                 par->pasteParagraph(bparams);
2627         }
2628         reinitLyXText();
2629 }