]> git.lyx.org Git - lyx.git/blob - src/insets/insettext.C
DISPATCH -> dispatch_result
[lyx.git] / src / insets / insettext.C
1 /**
2  * \file insettext.C
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Jürgen Vigna
7  *
8  * Full author contact details are available in file CREDITS.
9  */
10
11 #include <config.h>
12
13 #include "insettext.h"
14 #include "insetnewline.h"
15
16 #include "buffer.h"
17 #include "bufferparams.h"
18 #include "BufferView.h"
19 #include "CutAndPaste.h"
20 #include "debug.h"
21 #include "errorlist.h"
22 #include "funcrequest.h"
23 #include "gettext.h"
24 #include "intl.h"
25 #include "LColor.h"
26 #include "lyxfind.h"
27 #include "lyxlex.h"
28 #include "lyxrc.h"
29 #include "metricsinfo.h"
30 #include "paragraph.h"
31 #include "paragraph_funcs.h"
32 #include "ParagraphParameters.h"
33 #include "rowpainter.h"
34 #include "sgml.h"
35 #include "texrow.h"
36 #include "undo_funcs.h"
37 #include "WordLangTuple.h"
38
39 #include "frontends/Alert.h"
40 #include "frontends/font_metrics.h"
41 #include "frontends/LyXView.h"
42 #include "frontends/Painter.h"
43
44 #include "support/lyxalgo.h" // lyx::count
45
46 #include <boost/bind.hpp>
47
48 using bv_funcs::replaceSelection;
49
50 using lyx::pos_type;
51
52 using lyx::graphics::PreviewLoader;
53
54 using lyx::support::isStrUnsignedInt;
55 using lyx::support::strToUnsignedInt;
56
57 using std::endl;
58 using std::for_each;
59 using std::max;
60 using std::string;
61 using std::auto_ptr;
62 using std::ostream;
63 using std::vector;
64
65
66 InsetText::InsetText(BufferParams const & bp)
67         : UpdatableInset(),
68           paragraphs(1),
69           autoBreakRows_(false),
70           drawFrame_(NEVER),
71           frame_color_(LColor::insetframe),
72           text_(0, this, true, paragraphs)
73 {
74         textwidth_ = 0; // broken
75         paragraphs.begin()->layout(bp.getLyXTextClass().defaultLayout());
76         if (bp.tracking_changes)
77                 paragraphs.begin()->trackChanges();
78         init();
79 }
80
81
82 InsetText::InsetText(InsetText const & in)
83         : UpdatableInset(in),
84           text_(in.text_.bv_owner, this, true, paragraphs)
85 {
86         // this is ugly...
87         operator=(in);
88 }
89
90
91 void InsetText::operator=(InsetText const & in)
92 {
93         UpdatableInset::operator=(in);
94         paragraphs = in.paragraphs;
95         autoBreakRows_ = in.autoBreakRows_;
96         drawFrame_ = in.drawFrame_;
97         frame_color_ = in.frame_color_;
98         textwidth_ = in.textwidth_;
99         text_ = LyXText(in.text_.bv_owner, this, true, paragraphs);
100         init();
101 }
102
103
104 void InsetText::init()
105 {
106         ParagraphList::iterator pit = paragraphs.begin();
107         ParagraphList::iterator end = paragraphs.end();
108         for (; pit != end; ++pit)
109                 pit->setInsetOwner(this);
110         text_.paragraphs_ = &paragraphs;
111         top_y = 0;
112
113         locked = false;
114         inset_par = -1;
115         inset_pos = 0;
116         inset_x = 0;
117         inset_y = 0;
118         no_selection = true;
119         the_locking_inset = 0;
120         old_par = -1;
121         in_insetAllowed = false;
122         mouse_x = 0;
123         mouse_y = 0;
124 }
125
126
127 void InsetText::clear(bool just_mark_erased)
128 {
129         if (just_mark_erased) {
130                 ParagraphList::iterator it = paragraphs.begin();
131                 ParagraphList::iterator end = paragraphs.end();
132                 for (; it != end; ++it)
133                         it->markErased();
134                 return;
135         }
136
137         // This is a gross hack...
138         LyXLayout_ptr old_layout = paragraphs.begin()->layout();
139
140         paragraphs.clear();
141         paragraphs.push_back(Paragraph());
142         paragraphs.begin()->setInsetOwner(this);
143         paragraphs.begin()->layout(old_layout);
144 }
145
146
147 auto_ptr<InsetBase> InsetText::clone() const
148 {
149         return auto_ptr<InsetBase>(new InsetText(*this));
150 }
151
152
153 void InsetText::write(Buffer const & buf, ostream & os) const
154 {
155         os << "Text\n";
156         writeParagraphData(buf, os);
157 }
158
159
160 void InsetText::writeParagraphData(Buffer const & buf, ostream & os) const
161 {
162         ParagraphList::const_iterator it = paragraphs.begin();
163         ParagraphList::const_iterator end = paragraphs.end();
164         Paragraph::depth_type dth = 0;
165         for (; it != end; ++it) {
166                 it->write(buf, os, buf.params(), dth);
167         }
168 }
169
170
171 void InsetText::read(Buffer const & buf, LyXLex & lex)
172 {
173         string token;
174         Paragraph::depth_type depth = 0;
175
176         clear(false);
177
178 #warning John, look here. Doesnt make much sense.
179         if (buf.params().tracking_changes)
180                 paragraphs.begin()->trackChanges();
181
182         // delete the initial paragraph
183         Paragraph oldpar = *paragraphs.begin();
184         paragraphs.clear();
185         ParagraphList::iterator pit = paragraphs.begin();
186
187         while (lex.isOK()) {
188                 lex.nextToken();
189                 token = lex.getString();
190                 if (token.empty())
191                         continue;
192                 if (token == "\\end_inset") {
193                         break;
194                 }
195
196                 if (token == "\\end_document") {
197                         lex.printError("\\end_document read in inset! Error in document!");
198                         return;
199                 }
200
201                 // FIXME: ugly.
202                 const_cast<Buffer&>(buf).readParagraph(lex, token, paragraphs, pit, depth);
203         }
204
205         pit = paragraphs.begin();
206         ParagraphList::iterator const end = paragraphs.end();
207         for (; pit != end; ++pit)
208                 pit->setInsetOwner(this);
209
210         if (token != "\\end_inset") {
211                 lex.printError("Missing \\end_inset at this point. "
212                                            "Read: `$$Token'");
213         }
214
215         // sanity check
216         // ensure we have at least one par.
217         if (paragraphs.empty())
218                 paragraphs.push_back(oldpar);
219 }
220
221
222 void InsetText::metrics(MetricsInfo & mi, Dimension & dim) const
223 {
224         //lyxerr << "InsetText::metrics: width: " << mi.base.textwidth << endl;
225
226         textwidth_ = mi.base.textwidth;
227         BufferView * bv = mi.base.bv;
228         setViewCache(bv);
229         text_.metrics(mi, dim);
230         dim.asc += TEXT_TO_INSET_OFFSET;
231         dim.des += TEXT_TO_INSET_OFFSET;
232         dim.wid += 2 * TEXT_TO_INSET_OFFSET;
233         dim.wid = max(dim.wid, 10);
234         dim_ = dim;
235 }
236
237
238 int InsetText::textWidth() const
239 {
240         return textwidth_;
241 }
242
243
244 void InsetText::draw(PainterInfo & pi, int x, int y) const
245 {
246         // update our idea of where we are. Clearly, we should
247         // not have to know this information.
248         top_x = x;
249
250         int const start_x = x;
251
252         BufferView * bv = pi.base.bv;
253         Painter & pain = pi.pain;
254
255         // repaint the background if needed
256         if (backgroundColor() != LColor::background)
257                 clearInset(bv, start_x + TEXT_TO_INSET_OFFSET, y);
258
259         // no draw is necessary !!!
260         if (drawFrame_ == LOCKED && !locked && paragraphs.begin()->empty()) {
261                 top_baseline = y;
262                 return;
263         }
264
265         bv->hideCursor();
266
267         if (!owner())
268                 x += scroll();
269
270         top_baseline = y;
271         top_y = y - dim_.asc;
272
273         if (the_locking_inset
274                   && text_.cursor.par() == inset_par && cpos() == inset_pos) {
275                 inset_x = cx() - x;
276                 inset_y = cy();
277         }
278
279         x += TEXT_TO_INSET_OFFSET;
280
281         paintTextInset(*bv, text_, x, y);
282
283         if (drawFrame_ == ALWAYS || (drawFrame_ == LOCKED && locked))
284                 drawFrame(pain, start_x);
285 }
286
287
288 void InsetText::drawFrame(Painter & pain, int x) const
289 {
290         int const ttoD2 = TEXT_TO_INSET_OFFSET / 2;
291         int const frame_x = x + ttoD2;
292         int const frame_y = top_baseline - dim_.asc + ttoD2;
293         int const frame_w = dim_.wid - TEXT_TO_INSET_OFFSET;
294         int const frame_h = dim_.asc + dim_.des - TEXT_TO_INSET_OFFSET;
295         pain.rectangle(frame_x, frame_y, frame_w, frame_h, frameColor());
296 }
297
298
299 void InsetText::updateLocal(BufferView * bv, bool /*mark_dirty*/)
300 {
301         if (!bv)
302                 return;
303
304         if (!autoBreakRows_ && paragraphs.size() > 1)
305                 collapseParagraphs(bv);
306
307         if (!text_.selection.set())
308                 text_.selection.cursor = text_.cursor;
309
310         bv->fitCursor();
311         bv->updateInset(this);
312         bv->owner()->view_state_changed();
313         bv->owner()->updateMenubar();
314         bv->owner()->updateToolbar();
315         if (old_par != text_.cursor.par()) {
316                 bv->owner()->setLayout(cpar()->layout()->name());
317                 old_par = text_.cursor.par();
318         }
319 }
320
321
322 string const InsetText::editMessage() const
323 {
324         return _("Opened Text Inset");
325 }
326
327
328 void InsetText::insetUnlock(BufferView * bv)
329 {
330         if (the_locking_inset) {
331                 the_locking_inset->insetUnlock(bv);
332                 the_locking_inset = 0;
333                 updateLocal(bv, false);
334         }
335         no_selection = true;
336         locked = false;
337
338         if (text_.selection.set())
339                 text_.clearSelection();
340         else if (owner())
341                 bv->owner()->setLayout(owner()->getLyXText(bv)
342                                        ->cursorPar()->layout()->name());
343         else
344                 bv->owner()->setLayout(bv->text->cursorPar()->layout()->name());
345         // hack for deleteEmptyParMech
346         if (!paragraphs.begin()->empty())
347                 text_.setCursor(0, 0);
348         else if (paragraphs.size() > 1)
349                 text_.setCursor(1, 0);
350 }
351
352
353 void InsetText::lockInset(BufferView * bv)
354 {
355         locked = true;
356         the_locking_inset = 0;
357         inset_pos = inset_x = inset_y = 0;
358         inset_boundary = false;
359         inset_par =  -1;
360         old_par = -1;
361         text_.setCursorIntern(0, 0);
362         text_.clearSelection();
363         finishUndo();
364         // If the inset is empty set the language of the current font to the
365         // language to the surronding text (if different).
366         if (paragraphs.begin()->empty() && paragraphs.size() == 1 &&
367                 bv->getParentLanguage(this) != text_.current_font.language()) {
368                 LyXFont font(LyXFont::ALL_IGNORE);
369                 font.setLanguage(bv->getParentLanguage(this));
370                 setFont(bv, font, false);
371         }
372 }
373
374
375 void InsetText::lockInset(BufferView * /*bv*/, UpdatableInset * inset)
376 {
377         the_locking_inset = inset;
378         inset_x = cx() - top_x;
379         inset_y = cy();
380         inset_pos = cpos();
381         inset_par = text_.cursor.par();
382         inset_boundary = cboundary();
383 }
384
385
386 bool InsetText::lockInsetInInset(BufferView * bv, UpdatableInset * inset)
387 {
388         lyxerr[Debug::INSETS] << "InsetText::LockInsetInInset("
389                               << inset << "): " << endl;
390         if (!inset)
391                 return false;
392         if (!the_locking_inset) {
393                 ParagraphList::iterator pit = paragraphs.begin();
394                 ParagraphList::iterator pend = paragraphs.end();
395
396                 for (; pit != pend; ++pit) {
397                         InsetList::iterator it = pit->insetlist.begin();
398                         InsetList::iterator const end = pit->insetlist.end();
399                         for (; it != end; ++it) {
400                                 if (it->inset == inset) {
401                                         lyxerr << "InsetText::lockInsetInInset: 1 a" << endl;
402                                         text_.setCursorIntern(
403                                                 std::distance(paragraphs.begin(), pit), it->pos);
404                                         lyxerr << "InsetText::lockInsetInInset: 1 b" << endl;
405                                         lyxerr << "bv: " << bv << " inset: " << inset << endl;
406                                         lockInset(bv, inset);
407                                         lyxerr << "InsetText::lockInsetInInset: 1 c" << endl;
408                                         return true;
409                                 }
410                         }
411                 }
412                 lyxerr << "InsetText::lockInsetInInset: 3" << endl;
413                 return false;
414         }
415         if (inset == cpar()->getInset(cpos())) {
416                 lyxerr[Debug::INSETS] << "OK" << endl;
417                 lockInset(bv, inset);
418                 return true;
419         }
420
421         if (the_locking_inset && the_locking_inset == inset) {
422                 if (text_.cursor.par() == inset_par && cpos() == inset_pos) {
423                         lyxerr[Debug::INSETS] << "OK" << endl;
424                         inset_x = cx() - top_x;
425                         inset_y = cy();
426                 } else {
427                         lyxerr[Debug::INSETS] << "cursor.pos != inset_pos" << endl;
428                 }
429         } else if (the_locking_inset) {
430                 lyxerr[Debug::INSETS] << "MAYBE" << endl;
431                 return the_locking_inset->lockInsetInInset(bv, inset);
432         }
433         lyxerr[Debug::INSETS] << "NOT OK" << endl;
434         return false;
435 }
436
437
438 bool InsetText::unlockInsetInInset(BufferView * bv, UpdatableInset * inset,
439                                    bool lr)
440 {
441         if (!the_locking_inset)
442                 return false;
443         if (the_locking_inset == inset) {
444                 the_locking_inset->insetUnlock(bv);
445                 the_locking_inset = 0;
446                 if (lr)
447                         moveRightIntern(bv, true, false);
448                 old_par = -1; // force layout setting
449                 if (scroll())
450                         scroll(bv, 0.0F);
451                 else
452                         updateLocal(bv, false);
453                 return true;
454         }
455         return the_locking_inset->unlockInsetInInset(bv, inset, lr);
456 }
457
458
459 void InsetText::lfunMousePress(FuncRequest const & cmd)
460 {
461         no_selection = true;
462
463         // use this to check mouse motion for selection!
464         mouse_x = cmd.x;
465         mouse_y = cmd.y;
466
467         BufferView * bv = cmd.view();
468         FuncRequest cmd1 = cmd;
469         cmd1.x -= inset_x;
470         cmd1.y -= inset_y;
471         if (!locked)
472                 lockInset(bv);
473
474         int tmp_x = cmd.x;
475         int tmp_y = cmd.y + dim_.asc - bv->top_y();
476         InsetOld * inset = getLyXText(bv)->checkInsetHit(tmp_x, tmp_y);
477
478         if (the_locking_inset) {
479                 if (the_locking_inset == inset) {
480                         the_locking_inset->localDispatch(cmd1);
481                         return;
482                 }
483                 // otherwise only unlock the_locking_inset
484                 the_locking_inset->insetUnlock(bv);
485                 the_locking_inset = 0;
486         }
487         if (!inset)
488                 no_selection = false;
489
490         if (bv->theLockingInset()) {
491                 if (isHighlyEditableInset(inset)) {
492                         // We just have to lock the inset before calling a
493                         // PressEvent on it!
494                         UpdatableInset * uinset = static_cast<UpdatableInset*>(inset);
495                         if (!bv->lockInset(uinset)) {
496                                 lyxerr[Debug::INSETS] << "Cannot lock inset" << endl;
497                         }
498                         inset->localDispatch(cmd1);
499                         if (the_locking_inset)
500                                 updateLocal(bv, false);
501                         return;
502                 }
503         }
504         if (!inset) {
505                 bool paste_internally = false;
506                 if (cmd.button() == mouse_button::button2 && getLyXText(bv)->selection.set()) {
507                         localDispatch(FuncRequest(bv, LFUN_COPY));
508                         paste_internally = true;
509                 }
510                 int old_top_y = bv->top_y();
511
512                 text_.setCursorFromCoordinates(cmd.x, cmd.y + dim_.asc);
513                 // set the selection cursor!
514                 text_.selection.cursor = text_.cursor;
515                 text_.cursor.x_fix(text_.cursor.x());
516
517                 text_.clearSelection();
518                 updateLocal(bv, false);
519
520                 bv->owner()->setLayout(cpar()->layout()->name());
521
522                 // we moved the view we cannot do mouse selection in this case!
523                 if (bv->top_y() != old_top_y)
524                         no_selection = true;
525                 old_par = text_.cursor.par();
526                 // Insert primary selection with middle mouse
527                 // if there is a local selection in the current buffer,
528                 // insert this
529                 if (cmd.button() == mouse_button::button2) {
530                         if (paste_internally)
531                                 localDispatch(FuncRequest(bv, LFUN_PASTE));
532                         else
533                                 localDispatch(FuncRequest(bv, LFUN_PASTESELECTION, "paragraph"));
534                 }
535         } else {
536                 getLyXText(bv)->clearSelection();
537         }
538 }
539
540
541 bool InsetText::lfunMouseRelease(FuncRequest const & cmd)
542 {
543         BufferView * bv = cmd.view();
544         FuncRequest cmd1 = cmd;
545         cmd1.x -= inset_x;
546         cmd1.y -= inset_y;
547
548         no_selection = true;
549         if (the_locking_inset)
550                 return the_locking_inset->localDispatch(cmd1);
551
552         int tmp_x = cmd.x;
553         int tmp_y = cmd.y + dim_.asc - bv->top_y();
554         InsetOld * inset = getLyXText(bv)->checkInsetHit(tmp_x, tmp_y);
555         if (!inset)
556                 return false;
557
558         // We still need to deal properly with the whole relative vs.
559         // absolute mouse co-ords thing in a realiable, sensible way
560         bool ret = inset->localDispatch(cmd1);
561         updateLocal(bv, false);
562         return ret;
563 }
564
565
566 void InsetText::lfunMouseMotion(FuncRequest const & cmd)
567 {
568         FuncRequest cmd1 = cmd;
569         cmd1.x -= inset_x;
570         cmd1.y -= inset_y;
571
572         if (the_locking_inset) {
573                 the_locking_inset->localDispatch(cmd1);
574                 return;
575         }
576
577         if (no_selection || (mouse_x == cmd.x && mouse_y == cmd.y))
578                 return;
579
580         BufferView * bv = cmd.view();
581         LyXCursor cur = text_.cursor;
582         text_.setCursorFromCoordinates (cmd.x, cmd.y + dim_.asc);
583         text_.cursor.x_fix(text_.cursor.x());
584         if (cur == text_.cursor)
585                 return;
586         text_.setSelection();
587         updateLocal(bv, false);
588 }
589
590
591 dispatch_result InsetText::localDispatch(FuncRequest const & cmd)
592 {
593         BufferView * bv = cmd.view();
594         setViewCache(bv);
595
596         switch (cmd.action) {
597         case LFUN_INSET_EDIT: {
598                 UpdatableInset::localDispatch(cmd);
599
600                 if (!bv->lockInset(this)) {
601                         lyxerr[Debug::INSETS] << "Cannot lock inset" << endl;
602                         return DISPATCHED;
603                 }
604
605                 locked = true;
606                 the_locking_inset = 0;
607                 inset_pos = 0;
608                 inset_x = 0;
609                 inset_y = 0;
610                 inset_boundary = false;
611                 inset_par = -1;
612                 old_par = -1;
613
614
615                 if (cmd.argument.size()) {
616                         if (cmd.argument == "left")
617                                 text_.setCursorIntern(0, 0);
618                         else
619                                 text_.setCursor(paragraphs.size() - 1, paragraphs.back().size());
620                 } else {
621                         int tmp_y = (cmd.y < 0) ? 0 : cmd.y;
622                         // we put here -1 and not button as now the button in the
623                         // edit call should not be needed we will fix this in 1.3.x
624                         // cycle hopefully (Jug 20020509)
625                         // FIXME: GUII I've changed this to none: probably WRONG
626                         if (!checkAndActivateInset(bv, cmd.x, tmp_y, mouse_button::none)) {
627                                 text_.setCursorFromCoordinates(cmd.x, cmd.y + dim_.asc);
628                                 text_.cursor.x(text_.cursor.x());
629                                 text_.cursor.x_fix(text_.cursor.x());
630                         }
631                 }
632
633                 text_.clearSelection();
634                 finishUndo();
635
636                 // If the inset is empty set the language of the current font to the
637                 // language to the surronding text (if different).
638                 if (paragraphs.begin()->empty() &&
639                     paragraphs.size() == 1 &&
640                     bv->getParentLanguage(this) != text_.current_font.language())
641                 {
642                         LyXFont font(LyXFont::ALL_IGNORE);
643                         font.setLanguage(bv->getParentLanguage(this));
644                         setFont(bv, font, false);
645                 }
646
647                 updateLocal(bv, false);
648                 // Tell the paragraph dialog that we've entered an insettext.
649                 bv->dispatch(FuncRequest(LFUN_PARAGRAPH_UPDATE));
650                 return DISPATCHED;
651         }
652
653         case LFUN_MOUSE_PRESS:
654                 lfunMousePress(cmd);
655                 return DISPATCHED;
656
657         case LFUN_MOUSE_MOTION:
658                 lfunMouseMotion(cmd);
659                 return DISPATCHED;
660
661         case LFUN_MOUSE_RELEASE:
662                 return lfunMouseRelease(cmd) ? DISPATCHED : UNDISPATCHED;
663
664         default:
665                 break;
666         }
667
668         bool was_empty = paragraphs.begin()->empty() && paragraphs.size() == 1;
669         no_selection = false;
670
671         dispatch_result result = UpdatableInset::localDispatch(cmd);
672         if (result != UNDISPATCHED)
673                 return DISPATCHED;
674
675         result = DISPATCHED;
676         if (cmd.action < 0 && cmd.argument.empty())
677                 return FINISHED;
678
679         if (the_locking_inset) {
680                 result = the_locking_inset->localDispatch(cmd);
681                 if (result == DISPATCHED_NOUPDATE)
682                         return result;
683                 if (result == DISPATCHED) {
684                         updateLocal(bv, false);
685                         return result;
686                 }
687                 if (result >= FINISHED) {
688                         switch (result) {
689                         case FINISHED_RIGHT:
690                                 moveRightIntern(bv, false, false);
691                                 result = DISPATCHED;
692                                 break;
693                         case FINISHED_UP:
694                                 result = moveUp(bv);
695                                 if (result >= FINISHED) {
696                                         updateLocal(bv, false);
697                                         bv->unlockInset(this);
698                                 }
699                                 break;
700                         case FINISHED_DOWN:
701                                 result = moveDown(bv);
702                                 if (result >= FINISHED) {
703                                         updateLocal(bv, false);
704                                         bv->unlockInset(this);
705                                 }
706                                 break;
707                         default:
708                                 result = DISPATCHED;
709                                 break;
710                         }
711                         the_locking_inset = 0;
712                         updateLocal(bv, false);
713                         // make sure status gets reset immediately
714                         bv->owner()->clearMessage();
715                         return result;
716                 }
717         }
718         bool updflag = false;
719
720         switch (cmd.action) {
721
722         // Normal chars
723         case LFUN_SELFINSERT:
724                 if (bv->buffer()->isReadonly()) {
725 //          setErrorMessage(N_("Document is read only"));
726                         break;
727                 }
728                 if (!cmd.argument.empty()) {
729                         /* Automatically delete the currently selected
730                          * text and replace it with what is being
731                          * typed in now. Depends on lyxrc settings
732                          * "auto_region_delete", which defaults to
733                          * true (on). */
734 #if 0
735                         // This should not be needed here and is also WRONG!
736                         recordUndo(bv, Undo::INSERT, text_.cursorPar());
737 #endif
738                         bv->switchKeyMap();
739
740                         if (lyxrc.auto_region_delete && text_.selection.set())
741                                 text_.cutSelection(false, false);
742                         text_.clearSelection();
743
744                         for (string::size_type i = 0; i < cmd.argument.length(); ++i)
745                                 bv->owner()->getIntl().getTransManager().
746                                         TranslateAndInsert(cmd.argument[i], &text_);
747                 }
748                 text_.selection.cursor = text_.cursor;
749                 updflag = true;
750                 result = DISPATCHED_NOUPDATE;
751                 break;
752
753         // cursor movements that need special handling
754
755         case LFUN_RIGHT:
756                 result = moveRight(bv);
757                 finishUndo();
758                 break;
759         case LFUN_LEFT:
760                 finishUndo();
761                 result = moveLeft(bv);
762                 break;
763         case LFUN_DOWN:
764                 finishUndo();
765                 result = moveDown(bv);
766                 break;
767         case LFUN_UP:
768                 finishUndo();
769                 result = moveUp(bv);
770                 break;
771
772         case LFUN_PRIOR:
773                 if (crow() == text_.firstRow())
774                         result = FINISHED_UP;
775                 else {
776                         text_.cursorPrevious();
777                         text_.clearSelection();
778                         result = DISPATCHED_NOUPDATE;
779                 }
780                 break;
781
782         case LFUN_NEXT:
783                 if (crow() == text_.lastRow())
784                         result = FINISHED_DOWN;
785                 else {
786                         text_.cursorNext();
787                         text_.clearSelection();
788                         result = DISPATCHED_NOUPDATE;
789                 }
790                 break;
791
792         case LFUN_BACKSPACE:
793                 if (text_.selection.set())
794                         text_.cutSelection(true, false);
795                 else
796                         text_.backspace();
797                 updflag = true;
798                 break;
799
800         case LFUN_DELETE:
801                 if (text_.selection.set())
802                         text_.cutSelection(true, false);
803                 else
804                         text_.Delete();
805                 updflag = true;
806                 break;
807
808         case LFUN_PASTE:
809                 if (!autoBreakRows_) {
810                         if (CutAndPaste::nrOfParagraphs() > 1) {
811 #ifdef WITH_WARNINGS
812 #warning FIXME horrendously bad UI
813 #endif
814                                 Alert::error(_("Paste failed"), _("Cannot include more than one paragraph."));
815                         }
816                 } else {
817                         replaceSelection(bv->getLyXText());
818                         size_t sel_index = 0;
819                         string const & arg = cmd.argument;
820                         if (isStrUnsignedInt(arg)) {
821 #warning FIXME Check if the arg is in the domain of available selections.
822                                 sel_index = strToUnsignedInt(arg);
823                         }
824                         text_.pasteSelection(sel_index);
825                         // bug 393
826                         text_.clearSelection();
827                         updflag = true;
828                 }
829                 break;
830
831         case LFUN_BREAKPARAGRAPH:
832                 if (!autoBreakRows_) {
833                         result = DISPATCHED;
834                 } else {
835                         replaceSelection(bv->getLyXText());
836                         text_.breakParagraph(paragraphs, 0);
837                         updflag = true;
838                 }
839                 break;
840
841         case LFUN_BREAKPARAGRAPHKEEPLAYOUT:
842                 if (!autoBreakRows_) {
843                         result = DISPATCHED;
844                 } else {
845                         replaceSelection(bv->getLyXText());
846                         text_.breakParagraph(paragraphs, 1);
847                         updflag = true;
848                 }
849                 break;
850
851         case LFUN_BREAKLINE: {
852                 if (!autoBreakRows_) {
853                         result = DISPATCHED;
854                 } else {
855                         replaceSelection(bv->getLyXText());
856                         text_.insertInset(new InsetNewline);
857                         updflag = true;
858                 }
859                 break;
860         }
861
862         case LFUN_LAYOUT:
863                 // do not set layouts on non breakable textinsets
864                 if (autoBreakRows_) {
865                         string cur_layout = cpar()->layout()->name();
866
867                         // Derive layout number from given argument (string)
868                         // and current buffer's textclass (number).
869                         LyXTextClass const & tclass =
870                                 bv->buffer()->params().getLyXTextClass();
871                         string layout = cmd.argument;
872                         bool hasLayout = tclass.hasLayout(layout);
873
874                         // If the entry is obsolete, use the new one instead.
875                         if (hasLayout) {
876                                 string const & obs = tclass[layout]->obsoleted_by();
877                                 if (!obs.empty())
878                                         layout = obs;
879                         }
880
881                         // see if we found the layout number:
882                         if (!hasLayout) {
883                                 FuncRequest lf(LFUN_MESSAGE, N_("Layout ") + cmd.argument + N_(" not known"));
884                                 bv->owner()->dispatch(lf);
885                                 break;
886                         }
887
888                         if (cur_layout != layout) {
889                                 cur_layout = layout;
890                                 text_.setLayout(layout);
891                                 bv->owner()->setLayout(cpar()->layout()->name());
892                                 updflag = true;
893                         }
894                 } else {
895                         // reset the layout box
896                         bv->owner()->setLayout(cpar()->layout()->name());
897                 }
898                 break;
899
900         default:
901                 if (!bv->dispatch(cmd))
902                         result = UNDISPATCHED;
903                 break;
904         }
905
906         updateLocal(bv, updflag);
907
908         /// If the action has deleted all text in the inset, we need to change the
909         // language to the language of the surronding text.
910         if (!was_empty && paragraphs.begin()->empty() &&
911             paragraphs.size() == 1) {
912                 LyXFont font(LyXFont::ALL_IGNORE);
913                 font.setLanguage(bv->getParentLanguage(this));
914                 setFont(bv, font, false);
915         }
916
917         if (result >= FINISHED)
918                 bv->unlockInset(this);
919
920         if (result == DISPATCHED_NOUPDATE)
921                 result = DISPATCHED;
922         return result;
923 }
924
925
926 int InsetText::latex(Buffer const & buf, ostream & os,
927                      LatexRunParams const & runparams) const
928 {
929         TexRow texrow;
930         latexParagraphs(buf, paragraphs, os, texrow, runparams);
931         return texrow.rows();
932 }
933
934
935 int InsetText::ascii(Buffer const & buf, ostream & os, int linelen) const
936 {
937         unsigned int lines = 0;
938
939         ParagraphList::const_iterator beg = paragraphs.begin();
940         ParagraphList::const_iterator end = paragraphs.end();
941         ParagraphList::const_iterator it = beg;
942         for (; it != end; ++it) {
943                 string const tmp = buf.asciiParagraph(*it, linelen, it == beg);
944                 lines += lyx::count(tmp.begin(), tmp.end(), '\n');
945                 os << tmp;
946         }
947         return lines;
948 }
949
950
951 int InsetText::linuxdoc(Buffer const & buf, ostream & os) const
952 {
953         ParagraphList::iterator pit = const_cast<ParagraphList&>(paragraphs).begin();
954         ParagraphList::iterator pend = const_cast<ParagraphList&>(paragraphs).end();
955
956         // There is a confusion between the empty paragraph and the default paragraph
957         // The default paragraph is <p></p>, the empty paragraph is *empty*
958         // Since none of the floats of linuxdoc accepts standard paragraphs
959         // I disable them. I don't expect problems. (jamatos 2003/07/27)
960         for (; pit != pend; ++pit) {
961                 const string name = pit->layout()->latexname();
962                 if (name != "p")
963                         sgml::openTag(os, 1, 0, name);
964                 buf.simpleLinuxDocOnePar(os, pit, 0);
965                 if (name != "p")
966                         sgml::closeTag(os, 1, 0, name);
967         }
968         return 0;
969 }
970
971
972 int InsetText::docbook(Buffer const & buf, ostream & os, bool mixcont) const
973 {
974         unsigned int lines = 0;
975
976         vector<string> environment_stack(10);
977         vector<string> environment_inner(10);
978
979         int const command_depth = 0;
980         string item_name;
981
982         Paragraph::depth_type depth = 0; // paragraph depth
983
984         ParagraphList::iterator pit = const_cast<ParagraphList&>(paragraphs).begin();
985         ParagraphList::iterator pend = const_cast<ParagraphList&>(paragraphs).end();
986
987         for (; pit != pend; ++pit) {
988                 int desc_on = 0; // description mode
989
990                 LyXLayout_ptr const & style = pit->layout();
991
992                 // environment tag closing
993                 for (; depth > pit->params().depth(); --depth) {
994                         if (environment_inner[depth] != "!-- --") {
995                                 item_name = "listitem";
996                                 lines += sgml::closeTag(os, command_depth + depth, mixcont, item_name);
997                                 if (environment_inner[depth] == "varlistentry")
998                                         lines += sgml::closeTag(os, depth+command_depth, mixcont, environment_inner[depth]);
999                         }
1000                         lines += sgml::closeTag(os, depth + command_depth, mixcont, environment_stack[depth]);
1001                         environment_stack[depth].erase();
1002                         environment_inner[depth].erase();
1003                 }
1004
1005                 if (depth == pit->params().depth()
1006                    && environment_stack[depth] != style->latexname()
1007                    && !environment_stack[depth].empty()) {
1008                         if (environment_inner[depth] != "!-- --") {
1009                                 item_name= "listitem";
1010                                 lines += sgml::closeTag(os, command_depth+depth, mixcont, item_name);
1011                                 if (environment_inner[depth] == "varlistentry")
1012                                         lines += sgml::closeTag(os, depth + command_depth, mixcont, environment_inner[depth]);
1013                         }
1014
1015                         lines += sgml::closeTag(os, depth + command_depth, mixcont, environment_stack[depth]);
1016
1017                         environment_stack[depth].erase();
1018                         environment_inner[depth].erase();
1019                 }
1020
1021                 // Write opening SGML tags.
1022                 switch (style->latextype) {
1023                 case LATEX_PARAGRAPH:
1024                         lines += sgml::openTag(os, depth + command_depth, mixcont, style->latexname());
1025                         break;
1026
1027                 case LATEX_COMMAND:
1028                         buf.error(ErrorItem(_("Error"), _("LatexType Command not allowed here.\n"), pit->id(), 0, pit->size()));
1029                         return -1;
1030                         break;
1031
1032                 case LATEX_ENVIRONMENT:
1033                 case LATEX_ITEM_ENVIRONMENT:
1034                         if (depth < pit->params().depth()) {
1035                                 depth = pit->params().depth();
1036                                 environment_stack[depth].erase();
1037                         }
1038
1039                         if (environment_stack[depth] != style->latexname()) {
1040                                 if (environment_stack.size() == depth + 1) {
1041                                         environment_stack.push_back("!-- --");
1042                                         environment_inner.push_back("!-- --");
1043                                 }
1044                                 environment_stack[depth] = style->latexname();
1045                                 environment_inner[depth] = "!-- --";
1046                                 lines += sgml::openTag(os, depth + command_depth, mixcont, environment_stack[depth]);
1047                         } else {
1048                                 if (environment_inner[depth] != "!-- --") {
1049                                         item_name= "listitem";
1050                                         lines += sgml::closeTag(os, command_depth + depth, mixcont, item_name);
1051                                         if (environment_inner[depth] == "varlistentry")
1052                                                 lines += sgml::closeTag(os, depth + command_depth, mixcont, environment_inner[depth]);
1053                                 }
1054                         }
1055
1056                         if (style->latextype == LATEX_ENVIRONMENT) {
1057                                 if (!style->latexparam().empty()) {
1058                                         if (style->latexparam() == "CDATA")
1059                                                 os << "<![CDATA[";
1060                                         else
1061                                           lines += sgml::openTag(os, depth + command_depth, mixcont, style->latexparam());
1062                                 }
1063                                 break;
1064                         }
1065
1066                         desc_on = (style->labeltype == LABEL_MANUAL);
1067
1068                         environment_inner[depth] = desc_on ? "varlistentry" : "listitem";
1069                         lines += sgml::openTag(os, depth + 1 + command_depth, mixcont, environment_inner[depth]);
1070
1071                         item_name = desc_on ? "term" : "para";
1072                         lines += sgml::openTag(os, depth + 1 + command_depth, mixcont, item_name);
1073
1074                         break;
1075                 default:
1076                         lines += sgml::openTag(os, depth + command_depth, mixcont, style->latexname());
1077                         break;
1078                 }
1079
1080                 buf.simpleDocBookOnePar(os, pit, desc_on, depth + 1 + command_depth);
1081
1082                 string end_tag;
1083                 // write closing SGML tags
1084                 switch (style->latextype) {
1085                 case LATEX_ENVIRONMENT:
1086                         if (!style->latexparam().empty()) {
1087                                 if (style->latexparam() == "CDATA")
1088                                         os << "]]>";
1089                                 else
1090                                         lines += sgml::closeTag(os, depth + command_depth, mixcont, style->latexparam());
1091                         }
1092                         break;
1093                 case LATEX_ITEM_ENVIRONMENT:
1094                         if (desc_on == 1)
1095                                 break;
1096                         end_tag= "para";
1097                         lines += sgml::closeTag(os, depth + 1 + command_depth, mixcont, end_tag);
1098                         break;
1099                 case LATEX_PARAGRAPH:
1100                         lines += sgml::closeTag(os, depth + command_depth, mixcont, style->latexname());
1101                         break;
1102                 default:
1103                         lines += sgml::closeTag(os, depth + command_depth, mixcont, style->latexname());
1104                         break;
1105                 }
1106         }
1107
1108         // Close open tags
1109         for (int d = depth; d >= 0; --d) {
1110                 if (!environment_stack[depth].empty()) {
1111                         if (environment_inner[depth] != "!-- --") {
1112                                 item_name = "listitem";
1113                                 lines += sgml::closeTag(os, command_depth + depth, mixcont, item_name);
1114                                if (environment_inner[depth] == "varlistentry")
1115                                        lines += sgml::closeTag(os, depth + command_depth, mixcont, environment_inner[depth]);
1116                         }
1117
1118                         lines += sgml::closeTag(os, depth + command_depth, mixcont, environment_stack[depth]);
1119                 }
1120         }
1121
1122         return lines;
1123 }
1124
1125
1126 void InsetText::validate(LaTeXFeatures & features) const
1127 {
1128         for_each(paragraphs.begin(), paragraphs.end(),
1129                  boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1130 }
1131
1132
1133 void InsetText::getCursor(BufferView & bv, int & x, int & y) const
1134 {
1135         if (the_locking_inset) {
1136                 the_locking_inset->getCursor(bv, x, y);
1137                 return;
1138         }
1139         x = cx();
1140         y = cy() + InsetText::y();
1141 }
1142
1143
1144 void InsetText::getCursorPos(BufferView * bv, int & x, int & y) const
1145 {
1146         if (the_locking_inset) {
1147                 the_locking_inset->getCursorPos(bv, x, y);
1148                 return;
1149         }
1150         x = cx() - top_x - TEXT_TO_INSET_OFFSET;
1151         y = cy() - TEXT_TO_INSET_OFFSET;
1152 }
1153
1154
1155 int InsetText::insetInInsetY() const
1156 {
1157         if (!the_locking_inset)
1158                 return 0;
1159
1160         return inset_y + the_locking_inset->insetInInsetY();
1161 }
1162
1163
1164 void InsetText::fitInsetCursor(BufferView * bv) const
1165 {
1166         if (the_locking_inset) {
1167                 the_locking_inset->fitInsetCursor(bv);
1168                 return;
1169         }
1170
1171         LyXFont const font = text_.getFont(cpar(), cpos());
1172
1173         int const asc = font_metrics::maxAscent(font);
1174         int const desc = font_metrics::maxDescent(font);
1175
1176         bv->fitLockedInsetCursor(cx(), cy(), asc, desc);
1177 }
1178
1179
1180 dispatch_result InsetText::moveRight(BufferView * bv)
1181 {
1182         if (text_.cursorPar()->isRightToLeftPar(bv->buffer()->params()))
1183                 return moveLeftIntern(bv, false, true, false);
1184         else
1185                 return moveRightIntern(bv, true, true, false);
1186 }
1187
1188
1189 dispatch_result InsetText::moveLeft(BufferView * bv)
1190 {
1191         if (text_.cursorPar()->isRightToLeftPar(bv->buffer()->params()))
1192                 return moveRightIntern(bv, true, true, false);
1193         else
1194                 return moveLeftIntern(bv, false, true, false);
1195 }
1196
1197
1198 dispatch_result
1199 InsetText::moveRightIntern(BufferView * bv, bool front,
1200                            bool activate_inset, bool selecting)
1201 {
1202         ParagraphList::iterator c_par = cpar();
1203
1204         if (boost::next(c_par) == paragraphs.end() && cpos() >= c_par->size())
1205                 return FINISHED_RIGHT;
1206         if (activate_inset && checkAndActivateInset(bv, front))
1207                 return DISPATCHED;
1208         text_.cursorRight(bv);
1209         if (!selecting)
1210                 text_.clearSelection();
1211         return DISPATCHED_NOUPDATE;
1212 }
1213
1214
1215 dispatch_result
1216 InsetText::moveLeftIntern(BufferView * bv, bool front,
1217                           bool activate_inset, bool selecting)
1218 {
1219         if (cpar() == paragraphs.begin() && cpos() <= 0)
1220                 return FINISHED;
1221         text_.cursorLeft(bv);
1222         if (!selecting)
1223                 text_.clearSelection();
1224         if (activate_inset && checkAndActivateInset(bv, front))
1225                 return DISPATCHED;
1226         return DISPATCHED_NOUPDATE;
1227 }
1228
1229
1230 dispatch_result InsetText::moveUp(BufferView * bv)
1231 {
1232         if (crow() == text_.firstRow())
1233                 return FINISHED_UP;
1234         text_.cursorUp(bv);
1235         text_.clearSelection();
1236         return DISPATCHED_NOUPDATE;
1237 }
1238
1239
1240 dispatch_result InsetText::moveDown(BufferView * bv)
1241 {
1242         if (crow() == text_.lastRow())
1243                 return FINISHED_DOWN;
1244         text_.cursorDown(bv);
1245         text_.clearSelection();
1246         return DISPATCHED_NOUPDATE;
1247 }
1248
1249
1250 bool InsetText::insertInset(BufferView * bv, InsetOld * inset)
1251 {
1252         if (the_locking_inset) {
1253                 if (the_locking_inset->insetAllowed(inset))
1254                         return the_locking_inset->insertInset(bv, inset);
1255                 return false;
1256         }
1257         inset->setOwner(this);
1258         text_.insertInset(inset);
1259         bv->fitCursor();
1260         updateLocal(bv, true);
1261         return true;
1262 }
1263
1264
1265 bool InsetText::insetAllowed(InsetOld::Code code) const
1266 {
1267         // in_insetAllowed is a really gross hack,
1268         // to allow us to call the owner's insetAllowed
1269         // without stack overflow, which can happen
1270         // when the owner uses InsetCollapsable::insetAllowed()
1271         bool ret = true;
1272         if (in_insetAllowed)
1273                 return ret;
1274         in_insetAllowed = true;
1275         if (the_locking_inset)
1276                 ret = the_locking_inset->insetAllowed(code);
1277         else if (owner())
1278                 ret = owner()->insetAllowed(code);
1279         in_insetAllowed = false;
1280         return ret;
1281 }
1282
1283
1284 UpdatableInset * InsetText::getLockingInset() const
1285 {
1286         return the_locking_inset ? the_locking_inset->getLockingInset() :
1287                 const_cast<InsetText *>(this);
1288 }
1289
1290
1291 UpdatableInset * InsetText::getFirstLockingInsetOfType(InsetOld::Code c)
1292 {
1293         if (c == lyxCode())
1294                 return this;
1295         if (the_locking_inset)
1296                 return the_locking_inset->getFirstLockingInsetOfType(c);
1297         return 0;
1298 }
1299
1300
1301 bool InsetText::showInsetDialog(BufferView * bv) const
1302 {
1303         if (the_locking_inset)
1304                 return the_locking_inset->showInsetDialog(bv);
1305         return false;
1306 }
1307
1308
1309 void InsetText::getLabelList(Buffer const & buffer,
1310                              std::vector<string> & list) const
1311 {
1312         ParagraphList::const_iterator pit = paragraphs.begin();
1313         ParagraphList::const_iterator pend = paragraphs.end();
1314         for (; pit != pend; ++pit) {
1315                 InsetList::const_iterator beg = pit->insetlist.begin();
1316                 InsetList::const_iterator end = pit->insetlist.end();
1317                 for (; beg != end; ++beg)
1318                         beg->inset->getLabelList(buffer, list);
1319         }
1320 }
1321
1322
1323 void InsetText::setFont(BufferView * bv, LyXFont const & font, bool toggleall,
1324                         bool selectall)
1325 {
1326         if (the_locking_inset) {
1327                 the_locking_inset->setFont(bv, font, toggleall, selectall);
1328                 return;
1329         }
1330
1331         if ((paragraphs.size() == 1 && paragraphs.begin()->empty())
1332             || cpar()->empty()) {
1333                 text_.setFont(font, toggleall);
1334                 return;
1335         }
1336
1337
1338         if (text_.selection.set())
1339                 recordUndo(bv, Undo::ATOMIC, text_.cursorPar());
1340
1341         if (selectall) {
1342                 text_.cursorTop();
1343                 text_.selection.cursor = text_.cursor;
1344                 text_.cursorBottom();
1345                 text_.setSelection();
1346         }
1347
1348         text_.toggleFree(font, toggleall);
1349
1350         if (selectall)
1351                 text_.clearSelection();
1352
1353         bv->fitCursor();
1354         updateLocal(bv, true);
1355 }
1356
1357
1358 bool InsetText::checkAndActivateInset(BufferView * bv, bool front)
1359 {
1360         if (cpos() == cpar()->size())
1361                 return false;
1362         InsetOld * inset = cpar()->getInset(cpos());
1363         if (!isHighlyEditableInset(inset))
1364                 return false;
1365         FuncRequest cmd(bv, LFUN_INSET_EDIT, front ? "left" : "right");
1366         inset->localDispatch(cmd);
1367         if (!the_locking_inset)
1368                 return false;
1369         updateLocal(bv, false);
1370         return true;
1371 }
1372
1373
1374 bool InsetText::checkAndActivateInset(BufferView * bv, int x, int y,
1375                                       mouse_button::state button)
1376 {
1377         int dummyx = x;
1378         int dummyy = y + dim_.asc;
1379         InsetOld * inset = getLyXText(bv)->checkInsetHit(dummyx, dummyy);
1380         // we only do the edit() call if the inset was hit by the mouse
1381         // or if it is a highly editable inset. So we should call this
1382         // function from our own edit with button < 0.
1383         // FIXME: GUII jbl. I've changed this to ::none for now which is probably
1384         // WRONG
1385         if (button == mouse_button::none && !isHighlyEditableInset(inset))
1386                 return false;
1387
1388         if (!inset)
1389                 return false;
1390         if (x < 0)
1391                 x = dim_.wid;
1392         if (y < 0)
1393                 y = dim_.des;
1394         inset_x = cx() - top_x;
1395         inset_y = cy();
1396         FuncRequest cmd(bv, LFUN_INSET_EDIT, x - inset_x, y - inset_y, button);
1397         inset->localDispatch(cmd);
1398         if (!the_locking_inset)
1399                 return false;
1400         updateLocal(bv, false);
1401         return true;
1402 }
1403
1404
1405 void InsetText::markNew(bool track_changes)
1406 {
1407         ParagraphList::iterator pit = paragraphs.begin();
1408         ParagraphList::iterator end = paragraphs.end();
1409         for (; pit != end; ++pit) {
1410                 if (track_changes) {
1411                         pit->trackChanges();
1412                 } else {
1413                         // no-op when not tracking
1414                         pit->cleanChanges();
1415                 }
1416         }
1417 }
1418
1419
1420 void InsetText::setText(string const & data, LyXFont const & font)
1421 {
1422         clear(false);
1423         for (unsigned int i = 0; i < data.length(); ++i)
1424                 paragraphs.begin()->insertChar(i, data[i], font);
1425 }
1426
1427
1428 void InsetText::setAutoBreakRows(bool flag)
1429 {
1430         if (flag != autoBreakRows_) {
1431                 autoBreakRows_ = flag;
1432                 if (!flag)
1433                         removeNewlines();
1434         }
1435 }
1436
1437
1438 void InsetText::setDrawFrame(DrawFrame how)
1439 {
1440         drawFrame_ = how;
1441 }
1442
1443
1444 LColor_color InsetText::frameColor() const
1445 {
1446         return LColor::color(frame_color_);
1447 }
1448
1449
1450 void InsetText::setFrameColor(LColor_color col)
1451 {
1452         frame_color_ = col;
1453 }
1454
1455
1456 int InsetText::cx() const
1457 {
1458         int x = text_.cursor.x() + top_x + TEXT_TO_INSET_OFFSET;
1459         if (the_locking_inset) {
1460                 LyXFont font = text_.getFont(text_.cursorPar(), text_.cursor.pos());
1461                 if (font.isVisibleRightToLeft())
1462                         x -= the_locking_inset->width();
1463         }
1464         return x;
1465 }
1466
1467
1468 int InsetText::cy() const
1469 {
1470         return text_.cursor.y() - dim_.asc + TEXT_TO_INSET_OFFSET;
1471 }
1472
1473
1474 pos_type InsetText::cpos() const
1475 {
1476         return text_.cursor.pos();
1477 }
1478
1479
1480 ParagraphList::iterator InsetText::cpar() const
1481 {
1482         return text_.cursorPar();
1483 }
1484
1485
1486 bool InsetText::cboundary() const
1487 {
1488         return text_.cursor.boundary();
1489 }
1490
1491
1492 RowList::iterator InsetText::crow() const
1493 {
1494         return text_.cursorRow();
1495 }
1496
1497
1498 LyXText * InsetText::getLyXText(BufferView const * bv,
1499                                 bool const recursive) const
1500 {
1501         setViewCache(bv);
1502         if (recursive && the_locking_inset)
1503                 return the_locking_inset->getLyXText(bv, true);
1504         return &text_;
1505 }
1506
1507
1508 void InsetText::setViewCache(BufferView const * bv) const
1509 {
1510         if (bv) {
1511                 if (bv != text_.bv_owner) {
1512                         //lyxerr << "setting view cache from "
1513                         //      << text_.bv_owner << " to " << bv << "\n";
1514                         text_.init(const_cast<BufferView *>(bv));
1515                 }
1516                 text_.bv_owner = const_cast<BufferView *>(bv);
1517         }
1518 }
1519
1520
1521 void InsetText::deleteLyXText(BufferView * bv, bool recursive) const
1522 {
1523         if (recursive) {
1524                 /// then remove all LyXText in text-insets
1525                 for_each(const_cast<ParagraphList&>(paragraphs).begin(),
1526                          const_cast<ParagraphList&>(paragraphs).end(),
1527                          boost::bind(&Paragraph::deleteInsetsLyXText, _1, bv));
1528         }
1529 }
1530
1531
1532 void InsetText::removeNewlines()
1533 {
1534         ParagraphList::iterator it = paragraphs.begin();
1535         ParagraphList::iterator end = paragraphs.end();
1536         for (; it != end; ++it)
1537                 for (int i = 0; i < it->size(); ++i)
1538                         if (it->isNewline(i))
1539                                 it->erase(i);
1540 }
1541
1542
1543 int InsetText::scroll(bool recursive) const
1544 {
1545         int sx = UpdatableInset::scroll(false);
1546
1547         if (recursive && the_locking_inset)
1548                 sx += the_locking_inset->scroll(recursive);
1549
1550         return sx;
1551 }
1552
1553
1554 void InsetText::clearSelection(BufferView *)
1555 {
1556         text_.clearSelection();
1557 }
1558
1559
1560 void InsetText::clearInset(BufferView * bv, int start_x, int baseline) const
1561 {
1562         Painter & pain = bv->painter();
1563         int w = dim_.wid;
1564         int h = dim_.asc + dim_.des;
1565         int ty = baseline - dim_.asc;
1566
1567         if (ty < 0) {
1568                 h += ty;
1569                 ty = 0;
1570         }
1571         if (ty + h > pain.paperHeight())
1572                 h = pain.paperHeight();
1573         if (top_x + w > pain.paperWidth())
1574                 w = pain.paperWidth();
1575         pain.fillRectangle(start_x + 1, ty + 1, w - 3, h - 1, backgroundColor());
1576 }
1577
1578
1579 ParagraphList * InsetText::getParagraphs(int i) const
1580 {
1581         return (i == 0) ? const_cast<ParagraphList*>(&paragraphs) : 0;
1582 }
1583
1584
1585 LyXCursor const & InsetText::cursor(BufferView * bv) const
1586 {
1587         if (the_locking_inset)
1588                 return the_locking_inset->cursor(bv);
1589         return getLyXText(bv)->cursor;
1590 }
1591
1592
1593 InsetOld * InsetText::getInsetFromID(int id_arg) const
1594 {
1595         if (id_arg == id())
1596                 return const_cast<InsetText *>(this);
1597
1598         ParagraphList::const_iterator pit = paragraphs.begin();
1599         ParagraphList::const_iterator pend = paragraphs.end();
1600         for (; pit != pend; ++pit) {
1601                 InsetList::const_iterator it = pit->insetlist.begin();
1602                 InsetList::const_iterator end = pit->insetlist.end();
1603                 for (; it != end; ++it) {
1604                         if (it->inset->id() == id_arg)
1605                                 return it->inset;
1606                         InsetOld * in = it->inset->getInsetFromID(id_arg);
1607                         if (in)
1608                                 return in;
1609                 }
1610         }
1611         return 0;
1612 }
1613
1614
1615 WordLangTuple const
1616 InsetText::selectNextWordToSpellcheck(BufferView * bv, float & value) const
1617 {
1618         WordLangTuple word;
1619         if (the_locking_inset) {
1620                 word = the_locking_inset->selectNextWordToSpellcheck(bv, value);
1621                 if (!word.word().empty()) {
1622                         value += cy();
1623                         return word;
1624                 }
1625                 // we have to go on checking so move cursor to the next char
1626                 text_.cursor.pos(text_.cursor.pos() + 1);
1627         }
1628         word = text_.selectNextWordToSpellcheck(value);
1629         if (word.word().empty())
1630                 bv->unlockInset(const_cast<InsetText *>(this));
1631         else
1632                 value = cy();
1633         return word;
1634 }
1635
1636
1637 void InsetText::selectSelectedWord(BufferView * bv)
1638 {
1639         if (the_locking_inset) {
1640                 the_locking_inset->selectSelectedWord(bv);
1641                 return;
1642         }
1643         getLyXText(bv)->selectSelectedWord();
1644         updateLocal(bv, false);
1645 }
1646
1647
1648 bool InsetText::nextChange(BufferView * bv, lyx::pos_type & length)
1649 {
1650         if (the_locking_inset) {
1651                 if (the_locking_inset->nextChange(bv, length))
1652                         return true;
1653                 text_.cursorRight(true);
1654         }
1655         lyx::find::SearchResult result =
1656                 lyx::find::findNextChange(bv, &text_, length);
1657
1658         if (result == lyx::find::SR_FOUND) {
1659                 LyXCursor cur = text_.cursor;
1660                 bv->unlockInset(bv->theLockingInset());
1661                 if (bv->lockInset(this))
1662                         locked = true;
1663                 text_.cursor = cur;
1664                 text_.setSelectionRange(length);
1665                 updateLocal(bv, false);
1666         }
1667         return result != lyx::find::SR_NOT_FOUND;
1668 }
1669
1670
1671 bool InsetText::searchForward(BufferView * bv, string const & str,
1672                               bool cs, bool mw)
1673 {
1674         if (the_locking_inset) {
1675                 if (the_locking_inset->searchForward(bv, str, cs, mw))
1676                         return true;
1677                 text_.cursorRight(true);
1678         }
1679         lyx::find::SearchResult result =
1680                 lyx::find::find(bv, &text_, str, true, cs, mw);
1681
1682         if (result == lyx::find::SR_FOUND) {
1683                 LyXCursor cur = text_.cursor;
1684                 bv->unlockInset(bv->theLockingInset());
1685                 if (bv->lockInset(this))
1686                         locked = true;
1687                 text_.cursor = cur;
1688                 text_.setSelectionRange(str.length());
1689                 updateLocal(bv, false);
1690         }
1691         return result != lyx::find::SR_NOT_FOUND;
1692 }
1693
1694
1695 bool InsetText::searchBackward(BufferView * bv, string const & str,
1696                                bool cs, bool mw)
1697 {
1698         if (the_locking_inset) {
1699                 if (the_locking_inset->searchBackward(bv, str, cs, mw))
1700                         return true;
1701         }
1702         if (!locked) {
1703                 text_.setCursor(paragraphs.size() - 1, paragraphs.back().size());
1704         }
1705         lyx::find::SearchResult result =
1706                 lyx::find::find(bv, &text_, str, false, cs, mw);
1707
1708         if (result == lyx::find::SR_FOUND) {
1709                 LyXCursor cur = text_.cursor;
1710                 bv->unlockInset(bv->theLockingInset());
1711                 if (bv->lockInset(this))
1712                         locked = true;
1713                 text_.cursor = cur;
1714                 text_.setSelectionRange(str.length());
1715                 updateLocal(bv, false);
1716         }
1717         return result != lyx::find::SR_NOT_FOUND;
1718 }
1719
1720
1721 bool InsetText::checkInsertChar(LyXFont & font)
1722 {
1723         return owner() ? owner()->checkInsertChar(font) : true;
1724 }
1725
1726
1727 void InsetText::collapseParagraphs(BufferView * bv)
1728 {
1729         while (paragraphs.size() > 1) {
1730                 ParagraphList::iterator const first = paragraphs.begin();
1731                 ParagraphList::iterator second = first;
1732                 advance(second, 1);
1733                 size_t const first_par_size = first->size();
1734
1735                 if (!first->empty() &&
1736                     !second->empty() &&
1737                     !first->isSeparator(first_par_size - 1)) {
1738                         first->insertChar(first_par_size, ' ');
1739                 }
1740
1741 #warning probably broken
1742                 if (text_.selection.set()) {
1743                         if (text_.selection.start.par() == 1) {
1744                                 text_.selection.start.par(1);
1745                                 text_.selection.start.pos(text_.selection.start.pos() + first_par_size);
1746                         }
1747                         if (text_.selection.end.par() == 2) {
1748                                 text_.selection.end.par(1);
1749                                 text_.selection.end.pos(text_.selection.end.pos() + first_par_size);
1750                         }
1751                 }
1752
1753                 mergeParagraph(bv->buffer()->params(), paragraphs, first);
1754         }
1755 }
1756
1757
1758 void InsetText::getDrawFont(LyXFont & font) const
1759 {
1760         if (!owner())
1761                 return;
1762         owner()->getDrawFont(font);
1763 }
1764
1765
1766 void InsetText::appendParagraphs(Buffer * buffer, ParagraphList & plist)
1767 {
1768 #warning FIXME Check if Changes stuff needs changing here. (Lgb)
1769 // And it probably does. You have to take a look at this John. (Lgb)
1770 #warning John, have a look here. (Lgb)
1771         ParagraphList::iterator pit = plist.begin();
1772         ParagraphList::iterator ins = paragraphs.insert(paragraphs.end(), *pit);
1773         ++pit;
1774         mergeParagraph(buffer->params(), paragraphs, boost::prior(ins));
1775
1776         ParagraphList::iterator pend = plist.end();
1777         for (; pit != pend; ++pit)
1778                 paragraphs.push_back(*pit);
1779 }
1780
1781
1782 void InsetText::addPreview(PreviewLoader & loader) const
1783 {
1784         ParagraphList::const_iterator pit = paragraphs.begin();
1785         ParagraphList::const_iterator pend = paragraphs.end();
1786
1787         for (; pit != pend; ++pit) {
1788                 InsetList::const_iterator it  = pit->insetlist.begin();
1789                 InsetList::const_iterator end = pit->insetlist.end();
1790                 for (; it != end; ++it)
1791                         it->inset->addPreview(loader);
1792         }
1793 }