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