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