]> git.lyx.org Git - lyx.git/blob - src/BufferView.cpp
d7e7e1655e929deb8a5642f295cebfec57c7f543
[lyx.git] / src / BufferView.cpp
1 /**
2  * \file BufferView.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Alfredo Braunstein
7  * \author Lars Gullik Bjønnes
8  * \author John Levon
9  * \author André Pönitz
10  * \author Jürgen Vigna
11  *
12  * Full author contact details are available in file CREDITS.
13  */
14
15 #include <config.h>
16
17 #include "BufferView.h"
18
19 #include "Buffer.h"
20 #include "buffer_funcs.h"
21 #include "BufferList.h"
22 #include "BufferParams.h"
23 #include "CoordCache.h"
24 #include "Cursor.h"
25 #include "CutAndPaste.h"
26 #include "DispatchResult.h"
27 #include "EmbeddedFiles.h"
28 #include "ErrorList.h"
29 #include "factory.h"
30 #include "FloatList.h"
31 #include "FuncRequest.h"
32 #include "FuncStatus.h"
33 #include "Intl.h"
34 #include "InsetIterator.h"
35 #include "Language.h"
36 #include "LaTeXFeatures.h"
37 #include "LyX.h"
38 #include "lyxfind.h"
39 #include "LyXFunc.h"
40 #include "Layout.h"
41 #include "LyXRC.h"
42 #include "MetricsInfo.h"
43 #include "Paragraph.h"
44 #include "paragraph_funcs.h"
45 #include "ParagraphParameters.h"
46 #include "ParIterator.h"
47 #include "Session.h"
48 #include "Text.h"
49 #include "TextClass.h"
50 #include "TextMetrics.h"
51 #include "TexRow.h"
52 #include "VSpace.h"
53 #include "WordLangTuple.h"
54
55 #include "insets/InsetBibtex.h"
56 #include "insets/InsetCommand.h" // ChangeRefs
57 #include "insets/InsetRef.h"
58 #include "insets/InsetText.h"
59
60 #include "frontends/alert.h"
61 #include "frontends/Application.h"
62 #include "frontends/Delegates.h"
63 #include "frontends/FontMetrics.h"
64 #include "frontends/Painter.h"
65 #include "frontends/Selection.h"
66
67 #include "graphics/Previews.h"
68
69 #include "support/convert.h"
70 #include "support/debug.h"
71 #include "support/ExceptionMessage.h"
72 #include "support/FileFilterList.h"
73 #include "support/filetools.h"
74 #include "support/gettext.h"
75 #include "support/lstrings.h"
76 #include "support/Package.h"
77 #include "support/types.h"
78
79 #include <cerrno>
80 #include <fstream>
81 #include <functional>
82 #include <iterator>
83 #include <vector>
84
85 using namespace std;
86 using namespace lyx::support;
87
88 namespace lyx {
89
90 namespace Alert = frontend::Alert;
91
92 namespace {
93
94 /// Return an inset of this class if it exists at the current cursor position
95 template <class T>
96 T * getInsetByCode(Cursor const & cur, InsetCode code)
97 {
98         DocIterator it = cur;
99         Inset * inset = it.nextInset();
100         if (inset && inset->lyxCode() == code)
101                 return static_cast<T*>(inset);
102         return 0;
103 }
104
105
106 bool findInset(DocIterator & dit, vector<InsetCode> const & codes,
107         bool same_content);
108
109 bool findNextInset(DocIterator & dit, vector<InsetCode> const & codes,
110         docstring const & contents)
111 {
112         DocIterator tmpdit = dit;
113
114         while (tmpdit) {
115                 Inset const * inset = tmpdit.nextInset();
116                 if (inset
117                     && find(codes.begin(), codes.end(), inset->lyxCode()) != codes.end()
118                     && (contents.empty() ||
119                     static_cast<InsetCommand const *>(inset)->getFirstNonOptParam() == contents)) {
120                         dit = tmpdit;
121                         return true;
122                 }
123                 tmpdit.forwardInset();
124         }
125
126         return false;
127 }
128
129
130 /// Looks for next inset with one of the given codes.
131 bool findInset(DocIterator & dit, vector<InsetCode> const & codes,
132         bool same_content)
133 {
134         docstring contents;
135         DocIterator tmpdit = dit;
136         tmpdit.forwardInset();
137         if (!tmpdit)
138                 return false;
139
140         if (same_content) {
141                 Inset const * inset = tmpdit.nextInset();
142                 if (inset
143                     && find(codes.begin(), codes.end(), inset->lyxCode()) != codes.end()) {
144                         contents = static_cast<InsetCommand const *>(inset)->getFirstNonOptParam();
145                 }
146         }
147
148         if (!findNextInset(tmpdit, codes, contents)) {
149                 if (dit.depth() != 1 || dit.pit() != 0 || dit.pos() != 0) {
150                         tmpdit  = doc_iterator_begin(tmpdit.bottom().inset());
151                         if (!findNextInset(tmpdit, codes, contents))
152                                 return false;
153                 } else
154                         return false;
155         }
156
157         dit = tmpdit;
158         return true;
159 }
160
161
162 /// Looks for next inset with the given code
163 void findInset(DocIterator & dit, InsetCode code, bool same_content)
164 {
165         findInset(dit, vector<InsetCode>(1, code), same_content);
166 }
167
168
169 /// Moves cursor to the next inset with one of the given codes.
170 void gotoInset(BufferView * bv, vector<InsetCode> const & codes,
171                bool same_content)
172 {
173         Cursor tmpcur = bv->cursor();
174         if (!findInset(tmpcur, codes, same_content)) {
175                 bv->cursor().message(_("No more insets"));
176                 return;
177         }
178
179         tmpcur.clearSelection();
180         bv->setCursor(tmpcur);
181         bv->showCursor();
182 }
183
184
185 /// Moves cursor to the next inset with given code.
186 void gotoInset(BufferView * bv, InsetCode code, bool same_content)
187 {
188         gotoInset(bv, vector<InsetCode>(1, code), same_content);
189 }
190
191
192 /// A map from a Text to the associated text metrics
193 typedef map<Text const *, TextMetrics> TextMetricsCache;
194
195 enum ScreenUpdateStrategy {
196         NoScreenUpdate,
197         SingleParUpdate,
198         FullScreenUpdate,
199         DecorationUpdate
200 };
201
202 } // anon namespace
203
204
205 /////////////////////////////////////////////////////////////////////
206 //
207 // BufferView
208 //
209 /////////////////////////////////////////////////////////////////////
210
211 struct BufferView::Private
212 {
213         Private(BufferView & bv): wh_(0), cursor_(bv),
214                 anchor_pit_(0), anchor_ypos_(0),
215                 last_inset_(0), gui_(0)
216         {}
217
218         ///
219         ScrollbarParameters scrollbarParameters_;
220         ///
221         ScreenUpdateStrategy update_strategy_;
222         ///
223         CoordCache coord_cache_;
224
225         /// Estimated average par height for scrollbar.
226         int wh_;
227         /// this is used to handle XSelection events in the right manner.
228         struct {
229                 CursorSlice cursor;
230                 CursorSlice anchor;
231                 bool set;
232         } xsel_cache_;
233         ///
234         Cursor cursor_;
235         ///
236         pit_type anchor_pit_;
237         ///
238         int anchor_ypos_;
239         ///
240         vector<int> par_height_;
241
242         /// keyboard mapping object.
243         Intl intl_;
244
245         /// last visited inset.
246         /** kept to send setMouseHover(false).
247           * Not owned, so don't delete.
248           */
249         Inset * last_inset_;
250
251         mutable TextMetricsCache text_metrics_;
252
253         /// Whom to notify.
254         /** Not owned, so don't delete.
255           */
256         frontend::GuiBufferViewDelegate * gui_;
257 };
258
259
260 BufferView::BufferView(Buffer & buf)
261         : width_(0), height_(0), buffer_(buf), d(new Private(*this))
262 {
263         d->xsel_cache_.set = false;
264         d->intl_.initKeyMapper(lyxrc.use_kbmap);
265
266         d->cursor_.push(buffer_.inset());
267         d->cursor_.resetAnchor();
268         d->cursor_.setCurrentFont();
269
270         if (graphics::Previews::status() != LyXRC::PREVIEW_OFF)
271                 graphics::Previews::get().generateBufferPreviews(buffer_);
272 }
273
274
275 BufferView::~BufferView()
276 {
277         // current buffer is going to be switched-off, save cursor pos
278         // Ideally, the whole cursor stack should be saved, but session
279         // currently can only handle bottom (whole document) level pit and pos.
280         // That is to say, if a cursor is in a nested inset, it will be
281         // restore to the left of the top level inset.
282         LastFilePosSection::FilePos fp;
283         fp.pit = d->cursor_.bottom().pit();
284         fp.pos = d->cursor_.bottom().pos();
285         LyX::ref().session().lastFilePos().save(buffer_.fileName(), fp);
286
287         delete d;
288 }
289
290
291 Intl & BufferView::getIntl()
292 {
293         return d->intl_;
294 }
295
296
297 Intl const & BufferView::getIntl() const
298 {
299         return d->intl_;
300 }
301
302
303 CoordCache & BufferView::coordCache()
304 {
305         return d->coord_cache_;
306 }
307
308
309 CoordCache const & BufferView::coordCache() const
310 {
311         return d->coord_cache_;
312 }
313
314
315 Buffer & BufferView::buffer()
316 {
317         return buffer_;
318 }
319
320
321 Buffer const & BufferView::buffer() const
322 {
323         return buffer_;
324 }
325
326
327 bool BufferView::fitCursor()
328 {
329         if (cursorStatus(d->cursor_) == CUR_INSIDE) {
330                 frontend::FontMetrics const & fm =
331                         theFontMetrics(d->cursor_.getFont().fontInfo());
332                 int const asc = fm.maxAscent();
333                 int const des = fm.maxDescent();
334                 Point const p = getPos(d->cursor_, d->cursor_.boundary());
335                 if (p.y_ - asc >= 0 && p.y_ + des < height_)
336                         return false;
337         }
338         return true;
339 }
340
341
342 void BufferView::processUpdateFlags(Update::flags flags)
343 {
344         // last_inset_ points to the last visited inset. This pointer may become
345         // invalid because of keyboard editing. Since all such operations
346         // causes screen update(), I reset last_inset_ to avoid such a problem.
347         d->last_inset_ = 0;
348         // This is close to a hot-path.
349         LYXERR(Debug::DEBUG, "BufferView::processUpdateFlags()"
350                 << "[fitcursor = " << (flags & Update::FitCursor)
351                 << ", forceupdate = " << (flags & Update::Force)
352                 << ", singlepar = " << (flags & Update::SinglePar)
353                 << "]  buffer: " << &buffer_);
354
355         buffer_.updateMacros();
356
357         // Now do the first drawing step if needed. This consists on updating
358         // the CoordCache in updateMetrics().
359         // The second drawing step is done in WorkArea::redraw() if needed.
360
361         // Case when no explicit update is requested.
362         if (!flags) {
363                 // no need to redraw anything.
364                 d->update_strategy_ = NoScreenUpdate;
365                 return;
366         }
367
368         if (flags == Update::Decoration) {
369                 d->update_strategy_ = DecorationUpdate;
370                 buffer_.changed();
371                 return;
372         }
373
374         if (flags == Update::FitCursor
375                 || flags == (Update::Decoration | Update::FitCursor)) {
376                 // tell the frontend to update the screen if needed.
377                 if (fitCursor()) {
378                         showCursor();
379                         return;
380                 }
381                 if (flags & Update::Decoration) {
382                         d->update_strategy_ = DecorationUpdate;
383                         buffer_.changed();
384                         return;
385                 }
386                 // no screen update is needed.
387                 d->update_strategy_ = NoScreenUpdate;
388                 return;
389         }
390
391         bool const full_metrics = flags & Update::Force || !singleParUpdate();
392
393         if (full_metrics)
394                 // We have to update the full screen metrics.
395                 updateMetrics();
396
397         if (!(flags & Update::FitCursor)) {
398                 // Nothing to do anymore. Trigger a redraw and return
399                 buffer_.changed();
400                 return;
401         }
402
403         // updateMetrics() does not update paragraph position
404         // This is done at draw() time. So we need a redraw!
405         buffer_.changed();
406
407         if (fitCursor()) {
408                 // The cursor is off screen so ensure it is visible.
409                 // refresh it:
410                 showCursor();
411         }
412 }
413
414
415 void BufferView::updateScrollbar()
416 {
417         if (height_ == 0)
418                 return;
419
420         // We prefer fixed size line scrolling.
421         d->scrollbarParameters_.single_step = defaultRowHeight();
422         // We prefer full screen page scrolling.
423         d->scrollbarParameters_.page_step = height_;
424
425         Text & t = buffer_.text();
426         TextMetrics & tm = d->text_metrics_[&t];                
427
428         LYXERR(Debug::GUI, " Updating scrollbar: height: "
429                 << t.paragraphs().size()
430                 << " curr par: " << d->cursor_.bottom().pit()
431                 << " default height " << defaultRowHeight());
432
433         int const parsize = int(t.paragraphs().size());
434         if (d->par_height_.size() != parsize) {
435                 d->par_height_.clear();
436                 // FIXME: We assume a default paragraph height of 2 rows. This
437                 // should probably be pondered with the screen width.
438                 d->par_height_.resize(parsize, defaultRowHeight() * 2);
439         }
440
441         // Look at paragraph heights on-screen
442         pair<pit_type, ParagraphMetrics const *> first = tm.first();
443         pair<pit_type, ParagraphMetrics const *> last = tm.last();
444         for (pit_type pit = first.first; pit <= last.first; ++pit) {
445                 d->par_height_[pit] = tm.parMetrics(pit).height();
446                 LYXERR(Debug::SCROLLING, "storing height for pit " << pit << " : "
447                         << d->par_height_[pit]);
448         }
449
450         int top_pos = first.second->position() - first.second->ascent();
451         int bottom_pos = last.second->position() + last.second->descent();
452         bool first_visible = first.first == 0 && top_pos >= 0;
453         bool last_visible = last.first == parsize  - 1 && bottom_pos <= height_;
454         if (first_visible && last_visible) {
455                 d->scrollbarParameters_.min = 0;
456                 d->scrollbarParameters_.max = 0;
457                 return;
458         }
459
460         d->scrollbarParameters_.min = top_pos;
461         for (size_t i = 0; i != first.first; ++i)
462                 d->scrollbarParameters_.min -= d->par_height_[i];
463         d->scrollbarParameters_.max = bottom_pos;
464         for (size_t i = last.first + 1; i != parsize; ++i)
465                 d->scrollbarParameters_.max += d->par_height_[i];
466
467         d->scrollbarParameters_.position = 0;
468         // The reference is the top position so we remove one page.
469         d->scrollbarParameters_.max -= d->scrollbarParameters_.page_step;
470 }
471
472
473 ScrollbarParameters const & BufferView::scrollbarParameters() const
474 {
475         return d->scrollbarParameters_;
476 }
477
478
479 docstring BufferView::toolTip(int x, int y) const
480 {
481         // Get inset under mouse, if there is one.
482         Inset const * covering_inset = getCoveringInset(buffer_.text(), x, y);
483         if (!covering_inset)
484                 // No inset, no tooltip...
485                 return docstring();
486         return covering_inset->toolTip(*this, x, y);
487 }
488
489
490 docstring BufferView::contextMenu(int x, int y) const
491 {
492         // Get inset under mouse, if there is one.
493         Inset const * covering_inset = getCoveringInset(buffer_.text(), x, y);
494         if (covering_inset)
495                 return covering_inset->contextMenu(*this, x, y);
496
497         // FIXME: Do something more elaborate here.
498         return from_ascii("edit");
499 }
500
501
502 void BufferView::scrollDocView(int value)
503 {
504         // cut off at the top
505         if (value <= d->scrollbarParameters_.min) {
506                 DocIterator dit = doc_iterator_begin(buffer_.inset());
507                 showCursor(dit);
508                 LYXERR(Debug::SCROLLING, "scroll to top");
509                 return;
510         }
511
512         // cut off at the top
513         if (value >= d->scrollbarParameters_.max) {
514                 DocIterator dit = doc_iterator_end(buffer_.inset());
515                 dit.backwardPos();
516                 showCursor(dit);
517                 LYXERR(Debug::SCROLLING, "scroll to bottom");
518                 return;
519         }
520
521
522         int const offset = value - d->scrollbarParameters_.position;
523         // If the offset is less than 2 screen height, prefer to scroll instead.
524         if (abs(offset) <= 2 * height_) {
525                 scroll(offset);
526                 return;
527         }
528
529         // find paragraph at target positin
530         int par_pos = d->scrollbarParameters_.min;
531         for (size_t i = 0; i != d->par_height_.size(); ++i) {
532                 par_pos += d->par_height_[i];
533                 if (par_pos >= value) {
534                         d->anchor_pit_ = pit_type(i);
535                         break;
536                 }
537         }
538
539         LYXERR(Debug::SCROLLING, "value = " << value
540                 << "\tanchor_ref_ = " << d->anchor_pit_
541                 << "\tpar_pos = " << par_pos);
542
543         // cut off at the end of the buffer
544         if (value > par_pos) {
545                 value = d->scrollbarParameters_.max;
546                 d->anchor_pit_ = d->par_height_.size() - 1;
547         }
548
549         // set pixel offset of screen to anchor pit
550         d->anchor_ypos_ = par_pos - value;
551
552         updateMetrics();
553         buffer_.changed();
554 }
555
556
557 // FIXME: this method is not working well.
558 void BufferView::setCursorFromScrollbar()
559 {
560         TextMetrics & tm = d->text_metrics_[&buffer_.text()];
561
562         int const height = 2 * defaultRowHeight();
563         int const first = height;
564         int const last = height_ - height;
565         Cursor & cur = d->cursor_;
566
567         switch (cursorStatus(cur)) {
568         case CUR_ABOVE:
569                 // We reset the cursor because cursorStatus() does not
570                 // work when the cursor is within mathed.
571                 cur.reset(buffer_.inset());
572                 tm.setCursorFromCoordinates(cur, 0, first);
573                 cur.clearSelection();
574                 break;
575         case CUR_BELOW:
576                 // We reset the cursor because cursorStatus() does not
577                 // work when the cursor is within mathed.
578                 cur.reset(buffer_.inset());
579                 tm.setCursorFromCoordinates(cur, 0, last);
580                 cur.clearSelection();
581                 break;
582         case CUR_INSIDE:
583                 int const y = getPos(cur, cur.boundary()).y_;
584                 int const newy = min(last, max(y, first));
585                 if (y != newy) {
586                         cur.reset(buffer_.inset());
587                         tm.setCursorFromCoordinates(cur, 0, newy);
588                 }
589         }
590 }
591
592
593 Change const BufferView::getCurrentChange() const
594 {
595         if (!d->cursor_.selection())
596                 return Change(Change::UNCHANGED);
597
598         DocIterator dit = d->cursor_.selectionBegin();
599         return dit.paragraph().lookupChange(dit.pos());
600 }
601
602
603 // this could be used elsewhere as well?
604 // FIXME: This does not work within mathed!
605 CursorStatus BufferView::cursorStatus(DocIterator const & dit) const
606 {
607         Point const p = getPos(dit, dit.boundary());
608         if (p.y_ < 0)
609                 return CUR_ABOVE;
610         if (p.y_ > workHeight())
611                 return CUR_BELOW;
612         return CUR_INSIDE;
613 }
614
615
616 void BufferView::saveBookmark(unsigned int idx)
617 {
618         // tenatively save bookmark, id and pos will be used to
619         // acturately locate a bookmark in a 'live' lyx session.
620         // pit and pos will be updated with bottom level pit/pos
621         // when lyx exits.
622         LyX::ref().session().bookmarks().save(
623                 buffer_.fileName(),
624                 d->cursor_.bottom().pit(),
625                 d->cursor_.bottom().pos(),
626                 d->cursor_.paragraph().id(),
627                 d->cursor_.pos(),
628                 idx
629         );
630         if (idx)
631                 // emit message signal.
632                 message(_("Save bookmark"));
633 }
634
635
636 bool BufferView::moveToPosition(pit_type bottom_pit, pos_type bottom_pos,
637         int top_id, pos_type top_pos)
638 {
639         bool success = false;
640         DocIterator doc_it;
641
642         d->cursor_.clearSelection();
643
644         // if a valid par_id is given, try it first
645         // This is the case for a 'live' bookmark when unique paragraph ID
646         // is used to track bookmarks.
647         if (top_id > 0) {
648                 ParIterator par = buffer_.getParFromID(top_id);
649                 if (par != buffer_.par_iterator_end()) {
650                         doc_it = makeDocIterator(par, min(par->size(), top_pos));
651                         // Some slices of the iterator may not be
652                         // reachable (e.g. closed collapsable inset)
653                         // so the dociterator may need to be
654                         // shortened. Otherwise, setCursor may crash
655                         // lyx when the cursor can not be set to these
656                         // insets.
657                         size_t const n = doc_it.depth();
658                         for (size_t i = 0; i < n; ++i)
659                                 if (doc_it[i].inset().editable() != Inset::HIGHLY_EDITABLE) {
660                                         doc_it.resize(i);
661                                         break;
662                                 }
663                         success = true;
664                 }
665         }
666
667         // if top_id == 0, or searching through top_id failed
668         // This is the case for a 'restored' bookmark when only bottom
669         // (document level) pit was saved. Because of this, bookmark
670         // restoration is inaccurate. If a bookmark was within an inset,
671         // it will be restored to the left of the outmost inset that contains
672         // the bookmark.
673         if (static_cast<size_t>(bottom_pit) < buffer_.paragraphs().size()) {
674                 doc_it = doc_iterator_begin(buffer_.inset());
675                 doc_it.pit() = bottom_pit;
676                 doc_it.pos() = min(bottom_pos, doc_it.paragraph().size());
677                 success = true;
678         }
679
680         if (success) {
681                 // Note: only bottom (document) level pit is set.
682                 setCursor(doc_it);
683                 // set the current font.
684                 d->cursor_.setCurrentFont();
685                 // To center the screen on this new position we need the
686                 // paragraph position which is computed at draw() time.
687                 // So we need a redraw!
688                 buffer_.changed();
689                 if (fitCursor())
690                         showCursor();
691         }
692
693         return success;
694 }
695
696
697 void BufferView::translateAndInsert(char_type c, Text * t, Cursor & cur)
698 {
699         if (lyxrc.rtl_support) {
700                 if (d->cursor_.real_current_font.isRightToLeft()) {
701                         if (d->intl_.keymap == Intl::PRIMARY)
702                                 d->intl_.keyMapSec();
703                 } else {
704                         if (d->intl_.keymap == Intl::SECONDARY)
705                                 d->intl_.keyMapPrim();
706                 }
707         }
708
709         d->intl_.getTransManager().translateAndInsert(c, t, cur);
710 }
711
712
713 int BufferView::workWidth() const
714 {
715         return width_;
716 }
717
718
719 void BufferView::showCursor()
720 {
721         showCursor(d->cursor_);
722 }
723
724
725 void BufferView::showCursor(DocIterator const & dit)
726 {
727         // We are not properly started yet, delay until resizing is
728         // done.
729         if (height_ == 0)
730                 return;
731
732         LYXERR(Debug::SCROLLING, "recentering!");
733
734         CursorSlice const & bot = dit.bottom();
735         TextMetrics & tm = d->text_metrics_[bot.text()];
736
737         pos_type const max_pit = pos_type(bot.text()->paragraphs().size() - 1);
738         int bot_pit = bot.pit();
739         if (bot_pit > max_pit) {
740                 // FIXME: Why does this happen?
741                 LYXERR0("bottom pit is greater that max pit: "
742                         << bot_pit << " > " << max_pit);
743                 bot_pit = max_pit;
744         }
745
746         if (bot_pit == tm.first().first - 1)
747                 tm.newParMetricsUp();
748         else if (bot_pit == tm.last().first + 1)
749                 tm.newParMetricsDown();
750
751         if (tm.has(bot_pit)) {
752                 ParagraphMetrics const & pm = tm.parMetrics(bot_pit);
753                 BOOST_ASSERT(!pm.rows().empty());
754                 // FIXME: smooth scrolling doesn't work in mathed.
755                 CursorSlice const & cs = dit.innerTextSlice();
756                 int offset = coordOffset(dit, dit.boundary()).y_;
757                 int ypos = pm.position() + offset;
758                 Dimension const & row_dim =
759                         pm.getRow(cs.pos(), dit.boundary()).dimension();
760                 if (ypos - row_dim.ascent() < 0)
761                         scrollUp(- ypos + row_dim.ascent());
762                 else if (ypos + row_dim.descent() > height_)
763                         scrollDown(ypos - height_ + row_dim.descent());
764                 // else, nothing to do, the cursor is already visible so we just return.
765                 return;
766         }
767
768         tm.redoParagraph(bot_pit);
769         ParagraphMetrics const & pm = tm.parMetrics(bot_pit);
770         int offset = coordOffset(dit, dit.boundary()).y_;
771
772         d->anchor_pit_ = bot_pit;
773         CursorSlice const & cs = dit.innerTextSlice();
774         Dimension const & row_dim =
775                 pm.getRow(cs.pos(), dit.boundary()).dimension();
776
777         if (d->anchor_pit_ == 0)
778                 d->anchor_ypos_ = offset + pm.ascent();
779         else if (d->anchor_pit_ == max_pit)
780                 d->anchor_ypos_ = height_ - offset - row_dim.descent();
781         else
782                 d->anchor_ypos_ = defaultRowHeight() * 2 - offset - row_dim.descent();
783
784         updateMetrics();
785         buffer_.changed();
786 }
787
788
789 FuncStatus BufferView::getStatus(FuncRequest const & cmd)
790 {
791         FuncStatus flag;
792
793         Cursor & cur = d->cursor_;
794
795         switch (cmd.action) {
796
797         case LFUN_UNDO:
798                 flag.enabled(buffer_.undo().hasUndoStack());
799                 break;
800         case LFUN_REDO:
801                 flag.enabled(buffer_.undo().hasRedoStack());
802                 break;
803         case LFUN_FILE_INSERT:
804         case LFUN_FILE_INSERT_PLAINTEXT_PARA:
805         case LFUN_FILE_INSERT_PLAINTEXT:
806         case LFUN_BOOKMARK_SAVE:
807                 // FIXME: Actually, these LFUNS should be moved to Text
808                 flag.enabled(cur.inTexted());
809                 break;
810         case LFUN_FONT_STATE:
811         case LFUN_LABEL_INSERT:
812         case LFUN_INFO_INSERT:
813         case LFUN_PARAGRAPH_GOTO:
814         case LFUN_NOTE_NEXT:
815         case LFUN_REFERENCE_NEXT:
816         case LFUN_WORD_FIND:
817         case LFUN_WORD_REPLACE:
818         case LFUN_MARK_OFF:
819         case LFUN_MARK_ON:
820         case LFUN_MARK_TOGGLE:
821         case LFUN_SCREEN_RECENTER:
822         case LFUN_BIBTEX_DATABASE_ADD:
823         case LFUN_BIBTEX_DATABASE_DEL:
824         case LFUN_STATISTICS:
825         case LFUN_NEXT_INSET_TOGGLE:
826                 flag.enabled(true);
827                 break;
828
829         case LFUN_LABEL_GOTO: {
830                 flag.enabled(!cmd.argument().empty()
831                     || getInsetByCode<InsetRef>(cur, REF_CODE));
832                 break;
833         }
834
835         case LFUN_CHANGES_TRACK:
836                 flag.enabled(true);
837                 flag.setOnOff(buffer_.params().trackChanges);
838                 break;
839
840         case LFUN_CHANGES_OUTPUT:
841                 flag.enabled(true);
842                 flag.setOnOff(buffer_.params().outputChanges);
843                 break;
844
845         case LFUN_CHANGES_MERGE:
846         case LFUN_CHANGE_NEXT:
847         case LFUN_ALL_CHANGES_ACCEPT:
848         case LFUN_ALL_CHANGES_REJECT:
849                 // TODO: context-sensitive enabling of LFUNs
850                 // In principle, these command should only be enabled if there
851                 // is a change in the document. However, without proper
852                 // optimizations, this will inevitably result in poor performance.
853                 flag.enabled(true);
854                 break;
855
856         case LFUN_BUFFER_TOGGLE_COMPRESSION: {
857                 flag.setOnOff(buffer_.params().compressed);
858                 break;
859         }
860         
861         case LFUN_BUFFER_TOGGLE_EMBEDDING: {
862                 flag.setOnOff(buffer_.params().embedded);
863                 break;
864         }
865
866         case LFUN_SCREEN_UP:
867         case LFUN_SCREEN_DOWN:
868         case LFUN_SCROLL:
869                 flag.enabled(true);
870                 break;
871
872         // FIXME: LFUN_SCREEN_DOWN_SELECT should be removed from
873         // everywhere else before this can enabled:
874         case LFUN_SCREEN_UP_SELECT:
875         case LFUN_SCREEN_DOWN_SELECT:
876                 flag.enabled(false);
877                 break;
878
879         case LFUN_LAYOUT_TABULAR:
880                 flag.enabled(cur.innerInsetOfType(TABULAR_CODE));
881                 break;
882
883         case LFUN_LAYOUT:
884         case LFUN_LAYOUT_PARAGRAPH:
885                 flag.enabled(cur.inset().forceDefaultParagraphs(cur.idx()));
886                 break;
887
888         case LFUN_INSET_SETTINGS: {
889                 InsetCode code = cur.inset().lyxCode();
890                 bool enable = false;
891                 switch (code) {
892                         case TABULAR_CODE:
893                                 enable = cmd.argument() == "tabular";
894                                 break;
895                         case ERT_CODE:
896                                 enable = cmd.argument() == "ert";
897                                 break;
898                         case FLOAT_CODE:
899                                 enable = cmd.argument() == "float";
900                                 break;
901                         case WRAP_CODE:
902                                 enable = cmd.argument() == "wrap";
903                                 break;
904                         case NOTE_CODE:
905                                 enable = cmd.argument() == "note";
906                                 break;
907                         case BRANCH_CODE:
908                                 enable = cmd.argument() == "branch";
909                                 break;
910                         case BOX_CODE:
911                                 enable = cmd.argument() == "box";
912                                 break;
913                         case LISTINGS_CODE:
914                                 enable = cmd.argument() == "listings";
915                                 break;
916                         default:
917                                 break;
918                 }
919                 flag.enabled(enable);
920                 break;
921         }
922
923         case LFUN_DIALOG_SHOW_NEW_INSET:
924                 flag.enabled(cur.inset().lyxCode() != ERT_CODE &&
925                         cur.inset().lyxCode() != LISTINGS_CODE);
926                 if (cur.inset().lyxCode() == CAPTION_CODE) {
927                         FuncStatus flag;
928                         if (cur.inset().getStatus(cur, cmd, flag))
929                                 return flag;
930                 }
931                 break;
932
933         default:
934                 flag.enabled(false);
935         }
936
937         return flag;
938 }
939
940
941 bool BufferView::dispatch(FuncRequest const & cmd)
942 {
943         //lyxerr << [ cmd = " << cmd << "]" << endl;
944
945         // Make sure that the cached BufferView is correct.
946         LYXERR(Debug::ACTION, " action[" << cmd.action << ']'
947                 << " arg[" << to_utf8(cmd.argument()) << ']'
948                 << " x[" << cmd.x << ']'
949                 << " y[" << cmd.y << ']'
950                 << " button[" << cmd.button() << ']');
951
952         Cursor & cur = d->cursor_;
953
954         switch (cmd.action) {
955
956         case LFUN_UNDO:
957                 cur.message(_("Undo"));
958                 cur.clearSelection();
959                 if (!cur.textUndo())
960                         cur.message(_("No further undo information"));
961                 else
962                         processUpdateFlags(Update::Force | Update::FitCursor);
963                 break;
964
965         case LFUN_REDO:
966                 cur.message(_("Redo"));
967                 cur.clearSelection();
968                 if (!cur.textRedo())
969                         cur.message(_("No further redo information"));
970                 else
971                         processUpdateFlags(Update::Force | Update::FitCursor);
972                 break;
973
974         case LFUN_FONT_STATE:
975                 cur.message(cur.currentState());
976                 break;
977
978         case LFUN_BOOKMARK_SAVE:
979                 saveBookmark(convert<unsigned int>(to_utf8(cmd.argument())));
980                 break;
981
982         case LFUN_LABEL_GOTO: {
983                 docstring label = cmd.argument();
984                 if (label.empty()) {
985                         InsetRef * inset =
986                                 getInsetByCode<InsetRef>(d->cursor_,
987                                                          REF_CODE);
988                         if (inset) {
989                                 label = inset->getParam("reference");
990                                 // persistent=false: use temp_bookmark
991                                 saveBookmark(0);
992                         }
993                 }
994
995                 if (!label.empty())
996                         gotoLabel(label);
997                 break;
998         }
999
1000         case LFUN_PARAGRAPH_GOTO: {
1001                 int const id = convert<int>(to_utf8(cmd.argument()));
1002                 int i = 0;
1003                 for (Buffer * b = &buffer_; i == 0 || b != &buffer_;
1004                         b = theBufferList().next(b)) {
1005
1006                         ParIterator par = b->getParFromID(id);
1007                         if (par == b->par_iterator_end()) {
1008                                 LYXERR(Debug::INFO, "No matching paragraph found! [" << id << "].");
1009                         } else {
1010                                 LYXERR(Debug::INFO, "Paragraph " << par->id()
1011                                         << " found in buffer `"
1012                                         << b->absFileName() << "'.");
1013
1014                                 if (b == &buffer_) {
1015                                         // Set the cursor
1016                                         setCursor(makeDocIterator(par, 0));
1017                                         showCursor();
1018                                 } else {
1019                                         // Switch to other buffer view and resend cmd
1020                                         theLyXFunc().dispatch(FuncRequest(
1021                                                 LFUN_BUFFER_SWITCH, b->absFileName()));
1022                                         theLyXFunc().dispatch(cmd);
1023                                 }
1024                                 break;
1025                         }
1026                         ++i;
1027                 }
1028                 break;
1029         }
1030
1031         case LFUN_NOTE_NEXT:
1032                 gotoInset(this, NOTE_CODE, false);
1033                 break;
1034
1035         case LFUN_REFERENCE_NEXT: {
1036                 vector<InsetCode> tmp;
1037                 tmp.push_back(LABEL_CODE);
1038                 tmp.push_back(REF_CODE);
1039                 gotoInset(this, tmp, true);
1040                 break;
1041         }
1042
1043         case LFUN_CHANGES_TRACK:
1044                 buffer_.params().trackChanges = !buffer_.params().trackChanges;
1045                 break;
1046
1047         case LFUN_CHANGES_OUTPUT:
1048                 buffer_.params().outputChanges = !buffer_.params().outputChanges;
1049                 if (buffer_.params().outputChanges) {
1050                         bool dvipost    = LaTeXFeatures::isAvailable("dvipost");
1051                         bool xcolorsoul = LaTeXFeatures::isAvailable("soul") &&
1052                                           LaTeXFeatures::isAvailable("xcolor");
1053
1054                         if (!dvipost && !xcolorsoul) {
1055                                 Alert::warning(_("Changes not shown in LaTeX output"),
1056                                                _("Changes will not be highlighted in LaTeX output, "
1057                                                  "because neither dvipost nor xcolor/soul are installed.\n"
1058                                                  "Please install these packages or redefine "
1059                                                  "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
1060                         } else if (!xcolorsoul) {
1061                                 Alert::warning(_("Changes not shown in LaTeX output"),
1062                                                _("Changes will not be highlighted in LaTeX output "
1063                                                  "when using pdflatex, because xcolor and soul are not installed.\n"
1064                                                  "Please install both packages or redefine "
1065                                                  "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
1066                         }
1067                 }
1068                 break;
1069
1070         case LFUN_CHANGE_NEXT:
1071                 findNextChange(this);
1072                 break;
1073
1074         case LFUN_CHANGES_MERGE:
1075                 if (findNextChange(this))
1076                         showDialog("changes");
1077                 break;
1078
1079         case LFUN_ALL_CHANGES_ACCEPT:
1080                 // select complete document
1081                 d->cursor_.reset(buffer_.inset());
1082                 d->cursor_.selHandle(true);
1083                 buffer_.text().cursorBottom(d->cursor_);
1084                 // accept everything in a single step to support atomic undo
1085                 buffer_.text().acceptOrRejectChanges(d->cursor_, Text::ACCEPT);
1086                 break;
1087
1088         case LFUN_ALL_CHANGES_REJECT:
1089                 // select complete document
1090                 d->cursor_.reset(buffer_.inset());
1091                 d->cursor_.selHandle(true);
1092                 buffer_.text().cursorBottom(d->cursor_);
1093                 // reject everything in a single step to support atomic undo
1094                 // Note: reject does not work recursively; the user may have to repeat the operation
1095                 buffer_.text().acceptOrRejectChanges(d->cursor_, Text::REJECT);
1096                 break;
1097
1098         case LFUN_WORD_FIND:
1099                 find(this, cmd);
1100                 break;
1101
1102         case LFUN_WORD_REPLACE: {
1103                 bool has_deleted = false;
1104                 if (cur.selection()) {
1105                         DocIterator beg = cur.selectionBegin();
1106                         DocIterator end = cur.selectionEnd();
1107                         if (beg.pit() == end.pit()) {
1108                                 for (pos_type p = beg.pos() ; p < end.pos() ; ++p) {
1109                                         if (cur.paragraph().isDeleted(p))
1110                                                 has_deleted = true;
1111                                 }
1112                         }
1113                 }
1114                 replace(this, cmd, has_deleted);
1115                 break;
1116         }
1117
1118         case LFUN_MARK_OFF:
1119                 cur.clearSelection();
1120                 cur.resetAnchor();
1121                 cur.message(from_utf8(N_("Mark off")));
1122                 break;
1123
1124         case LFUN_MARK_ON:
1125                 cur.clearSelection();
1126                 cur.mark() = true;
1127                 cur.resetAnchor();
1128                 cur.message(from_utf8(N_("Mark on")));
1129                 break;
1130
1131         case LFUN_MARK_TOGGLE:
1132                 cur.clearSelection();
1133                 if (cur.mark()) {
1134                         cur.mark() = false;
1135                         cur.message(from_utf8(N_("Mark removed")));
1136                 } else {
1137                         cur.mark() = true;
1138                         cur.message(from_utf8(N_("Mark set")));
1139                 }
1140                 cur.resetAnchor();
1141                 break;
1142
1143         case LFUN_SCREEN_RECENTER:
1144                 showCursor();
1145                 break;
1146
1147         case LFUN_BIBTEX_DATABASE_ADD: {
1148                 Cursor tmpcur = d->cursor_;
1149                 findInset(tmpcur, BIBTEX_CODE, false);
1150                 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1151                                                 BIBTEX_CODE);
1152                 if (inset) {
1153                         if (inset->addDatabase(to_utf8(cmd.argument())))
1154                                 buffer_.updateBibfilesCache();
1155                 }
1156                 break;
1157         }
1158
1159         case LFUN_BIBTEX_DATABASE_DEL: {
1160                 Cursor tmpcur = d->cursor_;
1161                 findInset(tmpcur, BIBTEX_CODE, false);
1162                 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1163                                                 BIBTEX_CODE);
1164                 if (inset) {
1165                         if (inset->delDatabase(to_utf8(cmd.argument())))
1166                                 buffer_.updateBibfilesCache();
1167                 }
1168                 break;
1169         }
1170
1171         case LFUN_STATISTICS: {
1172                 DocIterator from, to;
1173                 if (cur.selection()) {
1174                         from = cur.selectionBegin();
1175                         to = cur.selectionEnd();
1176                 } else {
1177                         from = doc_iterator_begin(buffer_.inset());
1178                         to = doc_iterator_end(buffer_.inset());
1179                 }
1180                 int const words = countWords(from, to);
1181                 int const chars = countChars(from, to, false);
1182                 int const chars_blanks = countChars(from, to, true);
1183                 docstring message;
1184                 if (cur.selection())
1185                         message = _("Statistics for the selection:");
1186                 else
1187                         message = _("Statistics for the document:");
1188                 message += "\n\n";
1189                 if (words != 1)
1190                         message += bformat(_("%1$d words"), words);
1191                 else
1192                         message += _("One word");
1193                 message += "\n";
1194                 if (chars_blanks != 1)
1195                         message += bformat(_("%1$d characters (including blanks)"),
1196                                           chars_blanks);
1197                 else
1198                         message += _("One character (including blanks)");
1199                 message += "\n";
1200                 if (chars != 1)
1201                         message += bformat(_("%1$d characters (excluding blanks)"),
1202                                           chars);
1203                 else
1204                         message += _("One character (excluding blanks)");
1205
1206                 Alert::information(_("Statistics"), message);
1207         }
1208                 break;
1209
1210         case LFUN_BUFFER_TOGGLE_COMPRESSION:
1211                 // turn compression on/off
1212                 buffer_.params().compressed = !buffer_.params().compressed;
1213                 break;
1214         
1215         case LFUN_BUFFER_TOGGLE_EMBEDDING: {
1216                 // turn embedding on/off
1217                 try {
1218                         buffer_.embeddedFiles().enable(!buffer_.params().embedded, buffer_);
1219                 } catch (ExceptionMessage const & message) {
1220                         Alert::error(message.title_, message.details_);
1221                 }
1222                 break;
1223         }
1224
1225         case LFUN_NEXT_INSET_TOGGLE: {
1226                 // this is the real function we want to invoke
1227                 FuncRequest tmpcmd = FuncRequest(LFUN_INSET_TOGGLE, cmd.origin);
1228                 // if there is an inset at cursor, see whether it
1229                 // wants to toggle.
1230                 Inset * inset = cur.nextInset();
1231                 if (inset) {
1232                         if (inset->isActive()) {
1233                                 Cursor tmpcur = cur;
1234                                 tmpcur.pushBackward(*inset);
1235                                 inset->dispatch(tmpcur, tmpcmd);
1236                                 if (tmpcur.result().dispatched()) {
1237                                         cur.dispatched();
1238                                 }
1239                         } else if (inset->editable() == Inset::IS_EDITABLE) {
1240                                 inset->edit(cur, true);
1241                         }
1242                 }
1243                 // if it did not work, try the underlying inset.
1244                 if (!cur.result().dispatched())
1245                         cur.dispatch(tmpcmd);
1246
1247                 if (!cur.result().dispatched())
1248                         // It did not work too; no action needed.
1249                         break;
1250                 cur.clearSelection();
1251                 processUpdateFlags(Update::SinglePar | Update::FitCursor);
1252                 break;
1253         }
1254
1255         case LFUN_SCREEN_UP:
1256         case LFUN_SCREEN_DOWN: {
1257                 Point p = getPos(cur, cur.boundary());
1258                 if (p.y_ < 0 || p.y_ > height_) {
1259                         // The cursor is off-screen so recenter before proceeding.
1260                         showCursor();
1261                         p = getPos(cur, cur.boundary());
1262                 }
1263                 scroll(cmd.action == LFUN_SCREEN_UP? - height_ : height_);
1264                 cur.reset(buffer_.inset());
1265                 d->text_metrics_[&buffer_.text()].editXY(cur, p.x_, p.y_);
1266                 //FIXME: what to do with cur.x_target()?
1267                 cur.finishUndo();
1268                 break;
1269         }
1270
1271         case LFUN_SCROLL:
1272                 lfunScroll(cmd);
1273                 break;
1274
1275         case LFUN_SCREEN_UP_SELECT:
1276         case LFUN_SCREEN_DOWN_SELECT: {
1277                 // Those two are not ready yet for consumption.
1278                 return false;
1279
1280                 cur.selHandle(true);
1281                 size_t initial_depth = cur.depth();
1282                 Point const p = getPos(cur, cur.boundary());
1283                 scroll(cmd.action == LFUN_SCREEN_UP_SELECT? - height_ : height_);
1284                 // FIXME: We need to verify if the cursor stayed within an inset...
1285                 //cur.reset(buffer_.inset());
1286                 d->text_metrics_[&buffer_.text()].editXY(cur, p.x_, p.y_);
1287                 cur.finishUndo();
1288                 while (cur.depth() > initial_depth) {
1289                         cur.forwardInset();
1290                 }
1291                 // FIXME: we need to do a redraw again because of the selection
1292                 // But no screen update is needed.
1293                 d->update_strategy_ = NoScreenUpdate;
1294                 buffer_.changed();
1295                 break;
1296         }
1297
1298         default:
1299                 return false;
1300         }
1301
1302         return true;
1303 }
1304
1305
1306 docstring const BufferView::requestSelection()
1307 {
1308         Cursor & cur = d->cursor_;
1309
1310         if (!cur.selection()) {
1311                 d->xsel_cache_.set = false;
1312                 return docstring();
1313         }
1314
1315         if (!d->xsel_cache_.set ||
1316             cur.top() != d->xsel_cache_.cursor ||
1317             cur.anchor_.top() != d->xsel_cache_.anchor)
1318         {
1319                 d->xsel_cache_.cursor = cur.top();
1320                 d->xsel_cache_.anchor = cur.anchor_.top();
1321                 d->xsel_cache_.set = cur.selection();
1322                 return cur.selectionAsString(false);
1323         }
1324         return docstring();
1325 }
1326
1327
1328 void BufferView::clearSelection()
1329 {
1330         d->cursor_.clearSelection();
1331         // Clear the selection buffer. Otherwise a subsequent
1332         // middle-mouse-button paste would use the selection buffer,
1333         // not the more current external selection.
1334         cap::clearSelection();
1335         d->xsel_cache_.set = false;
1336         // The buffer did not really change, but this causes the
1337         // redraw we need because we cleared the selection above.
1338         buffer_.changed();
1339 }
1340
1341
1342 void BufferView::resize(int width, int height)
1343 {
1344         // Update from work area
1345         width_ = width;
1346         height_ = height;
1347
1348         // Clear the paragraph height cache.
1349         d->par_height_.clear();
1350
1351         updateMetrics();
1352 }
1353
1354
1355 Inset const * BufferView::getCoveringInset(Text const & text,
1356                 int x, int y) const
1357 {
1358         TextMetrics & tm = d->text_metrics_[&text];
1359         Inset * inset = tm.checkInsetHit(x, y);
1360         if (!inset)
1361                 return 0;
1362
1363         if (!inset->descendable())
1364                 // No need to go further down if the inset is not
1365                 // descendable.
1366                 return inset;
1367
1368         size_t cell_number = inset->nargs();
1369         // Check all the inner cell.
1370         for (size_t i = 0; i != cell_number; ++i) {
1371                 Text const * inner_text = inset->getText(i);
1372                 if (inner_text) {
1373                         // Try deeper.
1374                         Inset const * inset_deeper =
1375                                 getCoveringInset(*inner_text, x, y);
1376                         if (inset_deeper)
1377                                 return inset_deeper;
1378                 }
1379         }
1380
1381         return inset;
1382 }
1383
1384
1385 void BufferView::mouseEventDispatch(FuncRequest const & cmd0)
1386 {
1387         //lyxerr << "[ cmd0 " << cmd0 << "]" << endl;
1388
1389         // This is only called for mouse related events including
1390         // LFUN_FILE_OPEN generated by drag-and-drop.
1391         FuncRequest cmd = cmd0;
1392
1393         Cursor cur(*this);
1394         cur.push(buffer_.inset());
1395         cur.selection() = d->cursor_.selection();
1396
1397         // Either the inset under the cursor or the
1398         // surrounding Text will handle this event.
1399
1400         // make sure we stay within the screen...
1401         cmd.y = min(max(cmd.y, -1), height_);
1402
1403         if (cmd.action == LFUN_MOUSE_MOTION && cmd.button() == mouse_button::none) {
1404
1405                 // Get inset under mouse, if there is one.
1406                 Inset const * covering_inset =
1407                         getCoveringInset(buffer_.text(), cmd.x, cmd.y);
1408                 if (covering_inset == d->last_inset_)
1409                         // Same inset, no need to do anything...
1410                         return;
1411
1412                 bool need_redraw = false;
1413                 // const_cast because of setMouseHover().
1414                 Inset * inset = const_cast<Inset *>(covering_inset);
1415                 if (d->last_inset_)
1416                         // Remove the hint on the last hovered inset (if any).
1417                         need_redraw |= d->last_inset_->setMouseHover(false);
1418                 if (inset)
1419                         // Highlighted the newly hovered inset (if any).
1420                         need_redraw |= inset->setMouseHover(true);
1421                 d->last_inset_ = inset;
1422                 if (!need_redraw)
1423                         return;
1424
1425                 LYXERR(Debug::PAINTING, "Mouse hover detected at: ("
1426                         << cmd.x << ", " << cmd.y << ")");
1427
1428                 d->update_strategy_ = DecorationUpdate;
1429
1430                 // This event (moving without mouse click) is not passed further.
1431                 // This should be changed if it is further utilized.
1432                 buffer_.changed();
1433                 return;
1434         }
1435
1436         // Build temporary cursor.
1437         Inset * inset = d->text_metrics_[&buffer_.text()].editXY(cur, cmd.x, cmd.y);
1438
1439         // Put anchor at the same position.
1440         cur.resetAnchor();
1441
1442         // Try to dispatch to an non-editable inset near this position
1443         // via the temp cursor. If the inset wishes to change the real
1444         // cursor it has to do so explicitly by using
1445         //  cur.bv().cursor() = cur;  (or similar)
1446         if (inset)
1447                 inset->dispatch(cur, cmd);
1448
1449         // Now dispatch to the temporary cursor. If the real cursor should
1450         // be modified, the inset's dispatch has to do so explicitly.
1451         if (!cur.result().dispatched())
1452                 cur.dispatch(cmd);
1453
1454         //Do we have a selection?
1455         theSelection().haveSelection(cursor().selection());
1456
1457         // If the command has been dispatched,
1458         if (cur.result().dispatched()
1459                 // an update is asked,
1460                 && cur.result().update())
1461                 processUpdateFlags(cur.result().update());
1462 }
1463
1464
1465 void BufferView::lfunScroll(FuncRequest const & cmd)
1466 {
1467         string const scroll_type = cmd.getArg(0);
1468         int const scroll_step = 
1469                 (scroll_type == "line")? d->scrollbarParameters_.single_step
1470                 : (scroll_type == "page")? d->scrollbarParameters_.page_step : 0;
1471         if (scroll_step == 0)
1472                 return;
1473         string const scroll_quantity = cmd.getArg(1);
1474         if (scroll_quantity == "up")
1475                 scrollUp(scroll_step);
1476         else if (scroll_quantity == "down")
1477                 scrollDown(scroll_step);
1478         else {
1479                 int const scroll_value = convert<int>(scroll_quantity);
1480                 if (scroll_value)
1481                         scroll(scroll_step * scroll_value);
1482         }
1483 }
1484
1485
1486 void BufferView::scroll(int y)
1487 {
1488         if (y > 0)
1489                 scrollDown(y);
1490         else if (y < 0)
1491                 scrollUp(-y);
1492 }
1493
1494
1495 void BufferView::scrollDown(int offset)
1496 {
1497         Text * text = &buffer_.text();
1498         TextMetrics & tm = d->text_metrics_[text];
1499         int ymax = height_ + offset;
1500         while (true) {
1501                 pair<pit_type, ParagraphMetrics const *> last = tm.last();
1502                 int bottom_pos = last.second->position() + last.second->descent();
1503                 if (last.first + 1 == int(text->paragraphs().size())) {
1504                         if (bottom_pos <= height_)
1505                                 return;
1506                         offset = min(offset, bottom_pos - height_);
1507                         break;
1508                 }
1509                 if (bottom_pos > ymax)
1510                         break;
1511                 tm.newParMetricsDown();
1512         }
1513         d->anchor_ypos_ -= offset;
1514         updateMetrics();
1515         buffer_.changed();
1516 }
1517
1518
1519 void BufferView::scrollUp(int offset)
1520 {
1521         Text * text = &buffer_.text();
1522         TextMetrics & tm = d->text_metrics_[text];
1523         int ymin = - offset;
1524         while (true) {
1525                 pair<pit_type, ParagraphMetrics const *> first = tm.first();
1526                 int top_pos = first.second->position() - first.second->ascent();
1527                 if (first.first == 0) {
1528                         if (top_pos >= 0)
1529                                 return;
1530                         offset = min(offset, - top_pos);
1531                         break;
1532                 }
1533                 if (top_pos < ymin)
1534                         break;
1535                 tm.newParMetricsUp();
1536         }
1537         d->anchor_ypos_ += offset;
1538         updateMetrics();
1539         buffer_.changed();
1540 }
1541
1542
1543 void BufferView::setCursorFromRow(int row)
1544 {
1545         int tmpid = -1;
1546         int tmppos = -1;
1547
1548         buffer_.texrow().getIdFromRow(row, tmpid, tmppos);
1549
1550         d->cursor_.reset(buffer_.inset());
1551         if (tmpid == -1)
1552                 buffer_.text().setCursor(d->cursor_, 0, 0);
1553         else
1554                 buffer_.text().setCursor(d->cursor_, buffer_.getParFromID(tmpid).pit(), tmppos);
1555 }
1556
1557
1558 void BufferView::gotoLabel(docstring const & label)
1559 {
1560         for (InsetIterator it = inset_iterator_begin(buffer_.inset()); it; ++it) {
1561                 vector<docstring> labels;
1562                 it->getLabelList(buffer_, labels);
1563                 if (find(labels.begin(), labels.end(), label) != labels.end()) {
1564                         setCursor(it);
1565                         showCursor();
1566                         return;
1567                 }
1568         }
1569 }
1570
1571
1572 TextMetrics const & BufferView::textMetrics(Text const * t) const
1573 {
1574         return const_cast<BufferView *>(this)->textMetrics(t);
1575 }
1576
1577
1578 TextMetrics & BufferView::textMetrics(Text const * t)
1579 {
1580         TextMetricsCache::iterator tmc_it  = d->text_metrics_.find(t);
1581         if (tmc_it == d->text_metrics_.end()) {
1582                 tmc_it = d->text_metrics_.insert(
1583                         make_pair(t, TextMetrics(this, const_cast<Text *>(t)))).first;
1584         }
1585         return tmc_it->second;
1586 }
1587
1588
1589 ParagraphMetrics const & BufferView::parMetrics(Text const * t,
1590                 pit_type pit) const
1591 {
1592         return textMetrics(t).parMetrics(pit);
1593 }
1594
1595
1596 int BufferView::workHeight() const
1597 {
1598         return height_;
1599 }
1600
1601
1602 void BufferView::setCursor(DocIterator const & dit)
1603 {
1604         size_t const n = dit.depth();
1605         for (size_t i = 0; i < n; ++i)
1606                 dit[i].inset().edit(d->cursor_, true);
1607
1608         d->cursor_.setCursor(dit);
1609         d->cursor_.selection() = false;
1610 }
1611
1612
1613 bool BufferView::checkDepm(Cursor & cur, Cursor & old)
1614 {
1615         // Would be wrong to delete anything if we have a selection.
1616         if (cur.selection())
1617                 return false;
1618
1619         bool need_anchor_change = false;
1620         bool changed = d->cursor_.text()->deleteEmptyParagraphMechanism(cur, old,
1621                 need_anchor_change);
1622
1623         if (need_anchor_change)
1624                 cur.resetAnchor();
1625
1626         if (!changed)
1627                 return false;
1628
1629         d->cursor_ = cur;
1630
1631         updateLabels(buffer_);
1632
1633         updateMetrics();
1634         buffer_.changed();
1635         return true;
1636 }
1637
1638
1639 bool BufferView::mouseSetCursor(Cursor & cur, bool select)
1640 {
1641         BOOST_ASSERT(&cur.bv() == this);
1642
1643         if (!select)
1644                 // this event will clear selection so we save selection for
1645                 // persistent selection
1646                 cap::saveSelection(cursor());
1647
1648         // Has the cursor just left the inset?
1649         bool badcursor = false;
1650         bool leftinset = (&d->cursor_.inset() != &cur.inset());
1651         if (leftinset)
1652                 badcursor = notifyCursorLeaves(d->cursor_, cur);
1653
1654         // FIXME: shift-mouse selection doesn't work well across insets.
1655         bool do_selection = select && &d->cursor_.anchor().inset() == &cur.inset();
1656
1657         // do the dEPM magic if needed
1658         // FIXME: (1) move this to InsetText::notifyCursorLeaves?
1659         // FIXME: (2) if we had a working InsetText::notifyCursorLeaves,
1660         // the leftinset bool would not be necessary (badcursor instead).
1661         bool update = leftinset;
1662         if (!do_selection && !badcursor && d->cursor_.inTexted())
1663                 update |= checkDepm(cur, d->cursor_);
1664
1665         // if the cursor was in an empty script inset and the new
1666         // position is in the nucleus of the inset, notifyCursorLeaves
1667         // will kill the script inset itself. So we check all the
1668         // elements of the cursor to make sure that they are correct.
1669         // For an example, see bug 2933:
1670         // http://bugzilla.lyx.org/show_bug.cgi?id=2933
1671         // The code below could maybe be moved to a DocIterator method.
1672         //lyxerr << "cur before " << cur <<endl;
1673         DocIterator dit(cur.inset());
1674         dit.push_back(cur.bottom());
1675         size_t i = 1;
1676         while (i < cur.depth() && dit.nextInset() == &cur[i].inset()) {
1677                 dit.push_back(cur[i]);
1678                 ++i;
1679         }
1680         //lyxerr << "5 cur after" << dit <<endl;
1681
1682         d->cursor_.setCursor(dit);
1683         d->cursor_.boundary(cur.boundary());
1684         if (do_selection)
1685                 d->cursor_.setSelection();
1686         else
1687                 d->cursor_.clearSelection();
1688
1689         d->cursor_.finishUndo();
1690         d->cursor_.setCurrentFont();
1691         return update;
1692 }
1693
1694
1695 void BufferView::putSelectionAt(DocIterator const & cur,
1696                                 int length, bool backwards)
1697 {
1698         d->cursor_.clearSelection();
1699
1700         setCursor(cur);
1701
1702         if (length) {
1703                 if (backwards) {
1704                         d->cursor_.pos() += length;
1705                         d->cursor_.setSelection(d->cursor_, -length);
1706                 } else
1707                         d->cursor_.setSelection(d->cursor_, length);
1708         }
1709 }
1710
1711
1712 Cursor & BufferView::cursor()
1713 {
1714         return d->cursor_;
1715 }
1716
1717
1718 Cursor const & BufferView::cursor() const
1719 {
1720         return d->cursor_;
1721 }
1722
1723
1724 pit_type BufferView::anchor_ref() const
1725 {
1726         return d->anchor_pit_;
1727 }
1728
1729
1730 bool BufferView::singleParUpdate()
1731 {
1732         Text & buftext = buffer_.text();
1733         pit_type const bottom_pit = d->cursor_.bottom().pit();
1734         TextMetrics & tm = textMetrics(&buftext);
1735         int old_height = tm.parMetrics(bottom_pit).height();
1736
1737         // In Single Paragraph mode, rebreak only
1738         // the (main text, not inset!) paragraph containing the cursor.
1739         // (if this paragraph contains insets etc., rebreaking will
1740         // recursively descend)
1741         tm.redoParagraph(bottom_pit);
1742         ParagraphMetrics const & pm = tm.parMetrics(bottom_pit);                
1743         if (pm.height() != old_height)
1744                 // Paragraph height has changed so we cannot proceed to
1745                 // the singlePar optimisation.
1746                 return false;
1747
1748         d->update_strategy_ = SingleParUpdate;
1749
1750         LYXERR(Debug::PAINTING, "\ny1: " << pm.position() - pm.ascent()
1751                 << " y2: " << pm.position() + pm.descent()
1752                 << " pit: " << bottom_pit
1753                 << " singlepar: 1");
1754         return true;
1755 }
1756
1757
1758 void BufferView::updateMetrics()
1759 {
1760         Text & buftext = buffer_.text();
1761         pit_type const npit = int(buftext.paragraphs().size());
1762
1763         // Clear out the position cache in case of full screen redraw,
1764         d->coord_cache_.clear();
1765
1766         // Clear out paragraph metrics to avoid having invalid metrics
1767         // in the cache from paragraphs not relayouted below
1768         // The complete text metrics will be redone.
1769         d->text_metrics_.clear();
1770
1771         TextMetrics & tm = textMetrics(&buftext);
1772
1773         // Rebreak anchor paragraph.
1774         tm.redoParagraph(d->anchor_pit_);
1775         ParagraphMetrics & anchor_pm = tm.par_metrics_[d->anchor_pit_];
1776         anchor_pm.setPosition(d->anchor_ypos_);
1777
1778         LYXERR(Debug::PAINTING, "metrics: "
1779                 << " anchor pit = " << d->anchor_pit_
1780                 << " anchor ypos = " << d->anchor_ypos_);
1781
1782         // Redo paragraphs above anchor if necessary.
1783         int y1 = d->anchor_ypos_ - anchor_pm.ascent();
1784         // We are now just above the anchor paragraph.
1785         pit_type pit1 = d->anchor_pit_ - 1;
1786         for (; pit1 >= 0 && y1 >= 0; --pit1) {
1787                 tm.redoParagraph(pit1);
1788                 ParagraphMetrics & pm = tm.par_metrics_[pit1];
1789                 y1 -= pm.descent();
1790                 // Save the paragraph position in the cache.
1791                 pm.setPosition(y1);
1792                 y1 -= pm.ascent();
1793         }
1794
1795         // Redo paragraphs below the anchor if necessary.
1796         int y2 = d->anchor_ypos_ + anchor_pm.descent();
1797         // We are now just below the anchor paragraph.
1798         pit_type pit2 = d->anchor_pit_ + 1;
1799         for (; pit2 < npit && y2 <= height_; ++pit2) {
1800                 tm.redoParagraph(pit2);
1801                 ParagraphMetrics & pm = tm.par_metrics_[pit2];
1802                 y2 += pm.ascent();
1803                 // Save the paragraph position in the cache.
1804                 pm.setPosition(y2);
1805                 y2 += pm.descent();
1806         }
1807
1808         LYXERR(Debug::PAINTING, "Metrics: "
1809                 << " anchor pit = " << d->anchor_pit_
1810                 << " anchor ypos = " << d->anchor_ypos_
1811                 << " y1 = " << y1
1812                 << " y2 = " << y2
1813                 << " pit1 = " << pit1
1814                 << " pit2 = " << pit2);
1815
1816         d->update_strategy_ = FullScreenUpdate;
1817
1818         if (lyxerr.debugging(Debug::WORKAREA)) {
1819                 LYXERR(Debug::WORKAREA, "BufferView::updateMetrics");
1820                 d->coord_cache_.dump();
1821         }
1822 }
1823
1824
1825 void BufferView::insertLyXFile(FileName const & fname)
1826 {
1827         BOOST_ASSERT(d->cursor_.inTexted());
1828
1829         // Get absolute path of file and add ".lyx"
1830         // to the filename if necessary
1831         FileName filename = fileSearch(string(), fname.absFilename(), "lyx");
1832
1833         docstring const disp_fn = makeDisplayPath(filename.absFilename());
1834         // emit message signal.
1835         message(bformat(_("Inserting document %1$s..."), disp_fn));
1836
1837         docstring res;
1838         Buffer buf("", false);
1839         if (buf.loadLyXFile(filename)) {
1840                 ErrorList & el = buffer_.errorList("Parse");
1841                 // Copy the inserted document error list into the current buffer one.
1842                 el = buf.errorList("Parse");
1843                 buffer_.undo().recordUndo(d->cursor_);
1844                 cap::pasteParagraphList(d->cursor_, buf.paragraphs(),
1845                                              buf.params().getTextClassPtr(), el);
1846                 res = _("Document %1$s inserted.");
1847         } else {
1848                 res = _("Could not insert document %1$s");
1849         }
1850
1851         updateMetrics();
1852         buffer_.changed();
1853         // emit message signal.
1854         message(bformat(res, disp_fn));
1855         buffer_.errors("Parse");
1856 }
1857
1858
1859 Point BufferView::coordOffset(DocIterator const & dit, bool boundary) const
1860 {
1861         int x = 0;
1862         int y = 0;
1863         int lastw = 0;
1864
1865         // Addup contribution of nested insets, from inside to outside,
1866         // keeping the outer paragraph for a special handling below
1867         for (size_t i = dit.depth() - 1; i >= 1; --i) {
1868                 CursorSlice const & sl = dit[i];
1869                 int xx = 0;
1870                 int yy = 0;
1871                 
1872                 // get relative position inside sl.inset()
1873                 sl.inset().cursorPos(*this, sl, boundary && (i + 1 == dit.depth()), xx, yy);
1874                 
1875                 // Make relative position inside of the edited inset relative to sl.inset()
1876                 x += xx;
1877                 y += yy;
1878                 
1879                 // In case of an RTL inset, the edited inset will be positioned to the left
1880                 // of xx:yy
1881                 if (sl.text()) {
1882                         bool boundary_i = boundary && i + 1 == dit.depth();
1883                         bool rtl = textMetrics(sl.text()).isRTL(sl, boundary_i);
1884                         if (rtl)
1885                                 x -= lastw;
1886                 }
1887
1888                 // remember width for the case that sl.inset() is positioned in an RTL inset
1889                 if (i && dit[i - 1].text()) {
1890                         // If this Inset is inside a Text Inset, retrieve the Dimension
1891                         // from the containing text instead of using Inset::dimension() which
1892                         // might not be implemented.
1893                         // FIXME (Abdel 23/09/2007): this is a bit messy because of the
1894                         // elimination of Inset::dim_ cache. This coordOffset() method needs
1895                         // to be rewritten in light of the new design.
1896                         Dimension const & dim = parMetrics(dit[i - 1].text(),
1897                                 dit[i - 1].pit()).insetDimension(&sl.inset());
1898                         lastw = dim.wid;
1899                 } else {
1900                         Dimension const dim = sl.inset().dimension(*this);
1901                         lastw = dim.wid;
1902                 }
1903                 
1904                 //lyxerr << "Cursor::getPos, i: "
1905                 // << i << " x: " << xx << " y: " << y << endl;
1906         }
1907
1908         // Add contribution of initial rows of outermost paragraph
1909         CursorSlice const & sl = dit[0];
1910         TextMetrics const & tm = textMetrics(sl.text());
1911         ParagraphMetrics const & pm = tm.parMetrics(sl.pit());
1912         BOOST_ASSERT(!pm.rows().empty());
1913         y -= pm.rows()[0].ascent();
1914 #if 1
1915         // FIXME: document this mess
1916         size_t rend;
1917         if (sl.pos() > 0 && dit.depth() == 1) {
1918                 int pos = sl.pos();
1919                 if (pos && boundary)
1920                         --pos;
1921 //              lyxerr << "coordOffset: boundary:" << boundary << " depth:" << dit.depth() << " pos:" << pos << " sl.pos:" << sl.pos() << endl;
1922                 rend = pm.pos2row(pos);
1923         } else
1924                 rend = pm.pos2row(sl.pos());
1925 #else
1926         size_t rend = pm.pos2row(sl.pos());
1927 #endif
1928         for (size_t rit = 0; rit != rend; ++rit)
1929                 y += pm.rows()[rit].height();
1930         y += pm.rows()[rend].ascent();
1931         
1932         TextMetrics const & bottom_tm = textMetrics(dit.bottom().text());
1933         
1934         // Make relative position from the nested inset now bufferview absolute.
1935         int xx = bottom_tm.cursorX(dit.bottom(), boundary && dit.depth() == 1);
1936         x += xx;
1937         
1938         // In the RTL case place the nested inset at the left of the cursor in 
1939         // the outer paragraph
1940         bool boundary_1 = boundary && 1 == dit.depth();
1941         bool rtl = bottom_tm.isRTL(dit.bottom(), boundary_1);
1942         if (rtl)
1943                 x -= lastw;
1944         
1945         return Point(x, y);
1946 }
1947
1948
1949 Point BufferView::getPos(DocIterator const & dit, bool boundary) const
1950 {
1951         CursorSlice const & bot = dit.bottom();
1952         TextMetrics const & tm = textMetrics(bot.text());
1953         if (!tm.has(bot.pit()))
1954                 return Point(-1, -1);
1955
1956         Point p = coordOffset(dit, boundary); // offset from outer paragraph
1957         p.y_ += tm.parMetrics(bot.pit()).position();
1958         return p;
1959 }
1960
1961
1962 void BufferView::draw(frontend::Painter & pain)
1963 {
1964         LYXERR(Debug::PAINTING, "\t\t*** START DRAWING ***");
1965         Text & text = buffer_.text();
1966         TextMetrics const & tm = d->text_metrics_[&text];
1967         int const y = tm.first().second->position();
1968         PainterInfo pi(this, pain);
1969
1970         switch (d->update_strategy_) {
1971
1972         case NoScreenUpdate:
1973                 // If no screen painting is actually needed, only some the different
1974                 // coordinates of insets and paragraphs needs to be updated.
1975                 pi.full_repaint = true;
1976                 pi.pain.setDrawingEnabled(false);
1977                 tm.draw(pi, 0, y);
1978                 break;
1979
1980         case SingleParUpdate:
1981                 pi.full_repaint = false;
1982                 // In general, only the current row of the outermost paragraph
1983                 // will be redrawn. Particular cases where selection spans
1984                 // multiple paragraph are correctly detected in TextMetrics.
1985                 tm.draw(pi, 0, y);
1986                 break;
1987
1988         case DecorationUpdate:
1989                 // FIXME: We should also distinguish DecorationUpdate to avoid text
1990                 // drawing if possible. This is not possible to do easily right now
1991                 // because of the single backing pixmap.
1992
1993         case FullScreenUpdate:
1994                 // The whole screen, including insets, will be refreshed.
1995                 pi.full_repaint = true;
1996
1997                 // Clear background.
1998                 pain.fillRectangle(0, 0, width_, height_,
1999                         buffer_.inset().backgroundColor());
2000
2001                 // Draw everything.
2002                 tm.draw(pi, 0, y);
2003
2004                 // and possibly grey out below
2005                 pair<pit_type, ParagraphMetrics const *> lastpm = tm.last();
2006                 int const y2 = lastpm.second->position() + lastpm.second->descent();
2007                 if (y2 < height_)
2008                         pain.fillRectangle(0, y2, width_, height_ - y2, Color_bottomarea);
2009                 break;
2010         }
2011         LYXERR(Debug::PAINTING, "\n\t\t*** END DRAWING  ***");
2012
2013         // The scrollbar needs an update.
2014         updateScrollbar();
2015
2016         // Normalize anchor for next time
2017         pair<pit_type, ParagraphMetrics const *> firstpm = tm.first();
2018         pair<pit_type, ParagraphMetrics const *> lastpm = tm.last();
2019         for (pit_type pit = firstpm.first; pit <= lastpm.first; ++pit) {
2020                 ParagraphMetrics const & pm = tm.parMetrics(pit);
2021                 if (pm.position() + pm.descent() > 0) {
2022                         d->anchor_pit_ = pit;
2023                         d->anchor_ypos_ = pm.position();
2024                         break;
2025                 }
2026         }
2027         LYXERR(Debug::PAINTING, "Found new anchor pit = " << d->anchor_pit_
2028                 << "  anchor ypos = " << d->anchor_ypos_);
2029 }
2030
2031
2032 void BufferView::message(docstring const & msg)
2033 {
2034         if (d->gui_)
2035                 d->gui_->message(msg);
2036 }
2037
2038
2039 void BufferView::showDialog(string const & name)
2040 {
2041         if (d->gui_)
2042                 d->gui_->showDialog(name, string());
2043 }
2044
2045
2046 void BufferView::showDialog(string const & name,
2047         string const & data, Inset * inset)
2048 {
2049         if (d->gui_)
2050                 d->gui_->showDialog(name, data, inset);
2051 }
2052
2053
2054 void BufferView::updateDialog(string const & name, string const & data)
2055 {
2056         if (d->gui_)
2057                 d->gui_->updateDialog(name, data);
2058 }
2059
2060
2061 void BufferView::setGuiDelegate(frontend::GuiBufferViewDelegate * gui)
2062 {
2063         d->gui_ = gui;
2064 }
2065
2066
2067 // FIXME: Move this out of BufferView again
2068 docstring BufferView::contentsOfPlaintextFile(FileName const & fname)
2069 {
2070         if (!fname.isReadableFile()) {
2071                 docstring const error = from_ascii(strerror(errno));
2072                 docstring const file = makeDisplayPath(fname.absFilename(), 50);
2073                 docstring const text =
2074                   bformat(_("Could not read the specified document\n"
2075                             "%1$s\ndue to the error: %2$s"), file, error);
2076                 Alert::error(_("Could not read file"), text);
2077                 return docstring();
2078         }
2079
2080         if (!fname.isReadableFile()) {
2081                 docstring const file = makeDisplayPath(fname.absFilename(), 50);
2082                 docstring const text =
2083                   bformat(_("%1$s\n is not readable."), file);
2084                 Alert::error(_("Could not open file"), text);
2085                 return docstring();
2086         }
2087
2088         // FIXME UNICODE: We don't know the encoding of the file
2089         docstring file_content = fname.fileContents("UTF-8");
2090         if (file_content.empty()) {
2091                 Alert::error(_("Reading not UTF-8 encoded file"),
2092                              _("The file is not UTF-8 encoded.\n"
2093                                "It will be read as local 8Bit-encoded.\n"
2094                                "If this does not give the correct result\n"
2095                                "then please change the encoding of the file\n"
2096                                "to UTF-8 with a program other than LyX.\n"));
2097                 file_content = fname.fileContents("local8bit");
2098         }
2099
2100         return normalize_c(file_content);
2101 }
2102
2103
2104 void BufferView::insertPlaintextFile(FileName const & f, bool asParagraph)
2105 {
2106         docstring const tmpstr = contentsOfPlaintextFile(f);
2107
2108         if (tmpstr.empty())
2109                 return;
2110
2111         Cursor & cur = cursor();
2112         cap::replaceSelection(cur);
2113         buffer_.undo().recordUndo(cur);
2114         if (asParagraph)
2115                 cur.innerText()->insertStringAsParagraphs(cur, tmpstr);
2116         else
2117                 cur.innerText()->insertStringAsLines(cur, tmpstr);
2118
2119         updateMetrics();
2120         buffer_.changed();
2121 }
2122
2123 } // namespace lyx