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