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