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