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