]> git.lyx.org Git - lyx.git/blob - src/BufferView.cpp
This is the first of a series of commits that will make InsetLayout a real class.
[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.has(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 cur(*this);
1421         cur.push(buffer_.inset());
1422         cur.selection() = d->cursor_.selection();
1423
1424         // Either the inset under the cursor or the
1425         // surrounding Text will handle this event.
1426
1427         // make sure we stay within the screen...
1428         cmd.y = min(max(cmd.y, -1), height_);
1429
1430         if (cmd.action == LFUN_MOUSE_MOTION && cmd.button() == mouse_button::none) {
1431
1432                 // Get inset under mouse, if there is one.
1433                 Inset const * covering_inset =
1434                         getCoveringInset(buffer_.text(), cmd.x, cmd.y);
1435                 if (covering_inset == d->last_inset_)
1436                         // Same inset, no need to do anything...
1437                         return;
1438
1439                 bool need_redraw = false;
1440                 // const_cast because of setMouseHover().
1441                 Inset * inset = const_cast<Inset *>(covering_inset);
1442                 if (d->last_inset_)
1443                         // Remove the hint on the last hovered inset (if any).
1444                         need_redraw |= d->last_inset_->setMouseHover(false);
1445                 if (inset)
1446                         // Highlighted the newly hovered inset (if any).
1447                         need_redraw |= inset->setMouseHover(true);
1448                 d->last_inset_ = inset;
1449                 if (!need_redraw)
1450                         return;
1451
1452                 LYXERR(Debug::PAINTING, "Mouse hover detected at: ("
1453                         << cmd.x << ", " << cmd.y << ")");
1454
1455                 d->update_strategy_ = DecorationUpdate;
1456
1457                 // This event (moving without mouse click) is not passed further.
1458                 // This should be changed if it is further utilized.
1459                 buffer_.changed();
1460                 return;
1461         }
1462
1463         // Build temporary cursor.
1464         Inset * inset = d->text_metrics_[&buffer_.text()].editXY(cur, cmd.x, cmd.y);
1465
1466         // Put anchor at the same position.
1467         cur.resetAnchor();
1468
1469         // Try to dispatch to an non-editable inset near this position
1470         // via the temp cursor. If the inset wishes to change the real
1471         // cursor it has to do so explicitly by using
1472         //  cur.bv().cursor() = cur;  (or similar)
1473         if (inset)
1474                 inset->dispatch(cur, cmd);
1475
1476         // Now dispatch to the temporary cursor. If the real cursor should
1477         // be modified, the inset's dispatch has to do so explicitly.
1478         if (!cur.result().dispatched())
1479                 cur.dispatch(cmd);
1480
1481         //Do we have a selection?
1482         theSelection().haveSelection(cursor().selection());
1483
1484         // If the command has been dispatched,
1485         if (cur.result().dispatched()
1486                 // an update is asked,
1487                 && cur.result().update())
1488                 processUpdateFlags(cur.result().update());
1489 }
1490
1491
1492 void BufferView::lfunScroll(FuncRequest const & cmd)
1493 {
1494         string const scroll_type = cmd.getArg(0);
1495         int const scroll_step = 
1496                 (scroll_type == "line")? d->scrollbarParameters_.single_step
1497                 : (scroll_type == "page")? d->scrollbarParameters_.page_step : 0;
1498         if (scroll_step == 0)
1499                 return;
1500         string const scroll_quantity = cmd.getArg(1);
1501         if (scroll_quantity == "up")
1502                 scrollUp(scroll_step);
1503         else if (scroll_quantity == "down")
1504                 scrollDown(scroll_step);
1505         else {
1506                 int const scroll_value = convert<int>(scroll_quantity);
1507                 if (scroll_value)
1508                         scroll(scroll_step * scroll_value);
1509         }
1510 }
1511
1512
1513 void BufferView::scroll(int y)
1514 {
1515         if (y > 0)
1516                 scrollDown(y);
1517         else if (y < 0)
1518                 scrollUp(-y);
1519 }
1520
1521
1522 void BufferView::scrollDown(int offset)
1523 {
1524         Text * text = &buffer_.text();
1525         TextMetrics & tm = d->text_metrics_[text];
1526         int ymax = height_ + offset;
1527         while (true) {
1528                 pair<pit_type, ParagraphMetrics const *> last = tm.last();
1529                 int bottom_pos = last.second->position() + last.second->descent();
1530                 if (last.first + 1 == int(text->paragraphs().size())) {
1531                         if (bottom_pos <= height_)
1532                                 return;
1533                         offset = min(offset, bottom_pos - height_);
1534                         break;
1535                 }
1536                 if (bottom_pos > ymax)
1537                         break;
1538                 tm.newParMetricsDown();
1539         }
1540         d->anchor_ypos_ -= offset;
1541         updateMetrics();
1542         buffer_.changed();
1543 }
1544
1545
1546 void BufferView::scrollUp(int offset)
1547 {
1548         Text * text = &buffer_.text();
1549         TextMetrics & tm = d->text_metrics_[text];
1550         int ymin = - offset;
1551         while (true) {
1552                 pair<pit_type, ParagraphMetrics const *> first = tm.first();
1553                 int top_pos = first.second->position() - first.second->ascent();
1554                 if (first.first == 0) {
1555                         if (top_pos >= 0)
1556                                 return;
1557                         offset = min(offset, - top_pos);
1558                         break;
1559                 }
1560                 if (top_pos < ymin)
1561                         break;
1562                 tm.newParMetricsUp();
1563         }
1564         d->anchor_ypos_ += offset;
1565         updateMetrics();
1566         buffer_.changed();
1567 }
1568
1569
1570 void BufferView::setCursorFromRow(int row)
1571 {
1572         int tmpid = -1;
1573         int tmppos = -1;
1574
1575         buffer_.texrow().getIdFromRow(row, tmpid, tmppos);
1576
1577         d->cursor_.reset(buffer_.inset());
1578         if (tmpid == -1)
1579                 buffer_.text().setCursor(d->cursor_, 0, 0);
1580         else
1581                 buffer_.text().setCursor(d->cursor_, buffer_.getParFromID(tmpid).pit(), tmppos);
1582 }
1583
1584
1585 void BufferView::gotoLabel(docstring const & label)
1586 {
1587         for (InsetIterator it = inset_iterator_begin(buffer_.inset()); it; ++it) {
1588                 vector<docstring> labels;
1589                 it->getLabelList(buffer_, labels);
1590                 if (std::find(labels.begin(), labels.end(), label) != labels.end()) {
1591                         setCursor(it);
1592                         showCursor();
1593                         return;
1594                 }
1595         }
1596 }
1597
1598
1599 TextMetrics const & BufferView::textMetrics(Text const * t) const
1600 {
1601         return const_cast<BufferView *>(this)->textMetrics(t);
1602 }
1603
1604
1605 TextMetrics & BufferView::textMetrics(Text const * t)
1606 {
1607         TextMetricsCache::iterator tmc_it  = d->text_metrics_.find(t);
1608         if (tmc_it == d->text_metrics_.end()) {
1609                 tmc_it = d->text_metrics_.insert(
1610                         make_pair(t, TextMetrics(this, const_cast<Text *>(t)))).first;
1611         }
1612         return tmc_it->second;
1613 }
1614
1615
1616 ParagraphMetrics const & BufferView::parMetrics(Text const * t,
1617                 pit_type pit) const
1618 {
1619         return textMetrics(t).parMetrics(pit);
1620 }
1621
1622
1623 int BufferView::workHeight() const
1624 {
1625         return height_;
1626 }
1627
1628
1629 void BufferView::setCursor(DocIterator const & dit)
1630 {
1631         size_t const n = dit.depth();
1632         for (size_t i = 0; i < n; ++i)
1633                 dit[i].inset().edit(d->cursor_, true);
1634
1635         d->cursor_.setCursor(dit);
1636         d->cursor_.selection() = false;
1637 }
1638
1639
1640 bool BufferView::checkDepm(Cursor & cur, Cursor & old)
1641 {
1642         // Would be wrong to delete anything if we have a selection.
1643         if (cur.selection())
1644                 return false;
1645
1646         bool need_anchor_change = false;
1647         bool changed = d->cursor_.text()->deleteEmptyParagraphMechanism(cur, old,
1648                 need_anchor_change);
1649
1650         if (need_anchor_change)
1651                 cur.resetAnchor();
1652
1653         if (!changed)
1654                 return false;
1655
1656         d->cursor_ = cur;
1657
1658         updateLabels(buffer_);
1659
1660         updateMetrics();
1661         buffer_.changed();
1662         return true;
1663 }
1664
1665
1666 bool BufferView::mouseSetCursor(Cursor & cur, bool select)
1667 {
1668         BOOST_ASSERT(&cur.bv() == this);
1669
1670         if (!select)
1671                 // this event will clear selection so we save selection for
1672                 // persistent selection
1673                 cap::saveSelection(cursor());
1674
1675         // Has the cursor just left the inset?
1676         bool badcursor = false;
1677         bool leftinset = (&d->cursor_.inset() != &cur.inset());
1678         if (leftinset)
1679                 badcursor = notifyCursorLeaves(d->cursor_, cur);
1680
1681         // FIXME: shift-mouse selection doesn't work well across insets.
1682         bool do_selection = select && &d->cursor_.anchor().inset() == &cur.inset();
1683
1684         // do the dEPM magic if needed
1685         // FIXME: (1) move this to InsetText::notifyCursorLeaves?
1686         // FIXME: (2) if we had a working InsetText::notifyCursorLeaves,
1687         // the leftinset bool would not be necessary (badcursor instead).
1688         bool update = leftinset;
1689         if (!do_selection && !badcursor && d->cursor_.inTexted())
1690                 update |= checkDepm(cur, d->cursor_);
1691
1692         // if the cursor was in an empty script inset and the new
1693         // position is in the nucleus of the inset, notifyCursorLeaves
1694         // will kill the script inset itself. So we check all the
1695         // elements of the cursor to make sure that they are correct.
1696         // For an example, see bug 2933:
1697         // http://bugzilla.lyx.org/show_bug.cgi?id=2933
1698         // The code below could maybe be moved to a DocIterator method.
1699         //lyxerr << "cur before " << cur << endl;
1700         DocIterator dit = doc_iterator_begin(cur.inset());
1701         dit.bottom() = cur.bottom();
1702         size_t i = 1;
1703         while (i < cur.depth() && dit.nextInset() == &cur[i].inset()) {
1704                 dit.push_back(cur[i]);
1705                 ++i;
1706         }
1707         //lyxerr << "5 cur after" << dit <<endl;
1708
1709         d->cursor_.setCursor(dit);
1710         d->cursor_.boundary(cur.boundary());
1711         if (do_selection)
1712                 d->cursor_.setSelection();
1713         else
1714                 d->cursor_.clearSelection();
1715
1716         d->cursor_.finishUndo();
1717         d->cursor_.setCurrentFont();
1718         return update;
1719 }
1720
1721
1722 void BufferView::putSelectionAt(DocIterator const & cur,
1723                                 int length, bool backwards)
1724 {
1725         d->cursor_.clearSelection();
1726
1727         setCursor(cur);
1728
1729         if (length) {
1730                 if (backwards) {
1731                         d->cursor_.pos() += length;
1732                         d->cursor_.setSelection(d->cursor_, -length);
1733                 } else
1734                         d->cursor_.setSelection(d->cursor_, length);
1735         }
1736         // Ensure a redraw happens in any case because the new selection could 
1737         // possibly be on the same screen as the previous selection.
1738         processUpdateFlags(Update::Force | Update::FitCursor);
1739 }
1740
1741
1742 Cursor & BufferView::cursor()
1743 {
1744         return d->cursor_;
1745 }
1746
1747
1748 Cursor const & BufferView::cursor() const
1749 {
1750         return d->cursor_;
1751 }
1752
1753
1754 pit_type BufferView::anchor_ref() const
1755 {
1756         return d->anchor_pit_;
1757 }
1758
1759
1760 bool BufferView::singleParUpdate()
1761 {
1762         Text & buftext = buffer_.text();
1763         pit_type const bottom_pit = d->cursor_.bottom().pit();
1764         TextMetrics & tm = textMetrics(&buftext);
1765         int old_height = tm.parMetrics(bottom_pit).height();
1766
1767         // make sure inline completion pointer is ok
1768         if (d->inlineCompletionPos.fixIfBroken())
1769                 d->inlineCompletionPos = DocIterator();
1770
1771         // In Single Paragraph mode, rebreak only
1772         // the (main text, not inset!) paragraph containing the cursor.
1773         // (if this paragraph contains insets etc., rebreaking will
1774         // recursively descend)
1775         tm.redoParagraph(bottom_pit);
1776         ParagraphMetrics const & pm = tm.parMetrics(bottom_pit);                
1777         if (pm.height() != old_height)
1778                 // Paragraph height has changed so we cannot proceed to
1779                 // the singlePar optimisation.
1780                 return false;
1781
1782         d->update_strategy_ = SingleParUpdate;
1783
1784         LYXERR(Debug::PAINTING, "\ny1: " << pm.position() - pm.ascent()
1785                 << " y2: " << pm.position() + pm.descent()
1786                 << " pit: " << bottom_pit
1787                 << " singlepar: 1");
1788         return true;
1789 }
1790
1791
1792 void BufferView::updateMetrics()
1793 {
1794         Text & buftext = buffer_.text();
1795         pit_type const npit = int(buftext.paragraphs().size());
1796
1797         // Clear out the position cache in case of full screen redraw,
1798         d->coord_cache_.clear();
1799
1800         // Clear out paragraph metrics to avoid having invalid metrics
1801         // in the cache from paragraphs not relayouted below
1802         // The complete text metrics will be redone.
1803         d->text_metrics_.clear();
1804
1805         TextMetrics & tm = textMetrics(&buftext);
1806
1807         // make sure inline completion pointer is ok
1808         if (d->inlineCompletionPos.fixIfBroken())
1809                 d->inlineCompletionPos = DocIterator();
1810         
1811         // Rebreak anchor paragraph.
1812         tm.redoParagraph(d->anchor_pit_);
1813         ParagraphMetrics & anchor_pm = tm.par_metrics_[d->anchor_pit_];
1814         
1815         // position anchor
1816         if (d->anchor_pit_ == 0) {
1817                 int scrollRange = d->scrollbarParameters_.max - d->scrollbarParameters_.min;
1818                 
1819                 // Complete buffer visible? Then it's easy.
1820                 if (scrollRange == 0)
1821                         d->anchor_ypos_ = anchor_pm.ascent();
1822         
1823                 // FIXME: Some clever handling needed to show
1824                 // the _first_ paragraph up to the top if the cursor is
1825                 // in the first line.
1826         }               
1827         anchor_pm.setPosition(d->anchor_ypos_);
1828
1829         LYXERR(Debug::PAINTING, "metrics: "
1830                 << " anchor pit = " << d->anchor_pit_
1831                 << " anchor ypos = " << d->anchor_ypos_);
1832
1833         // Redo paragraphs above anchor if necessary.
1834         int y1 = d->anchor_ypos_ - anchor_pm.ascent();
1835         // We are now just above the anchor paragraph.
1836         pit_type pit1 = d->anchor_pit_ - 1;
1837         for (; pit1 >= 0 && y1 >= 0; --pit1) {
1838                 tm.redoParagraph(pit1);
1839                 ParagraphMetrics & pm = tm.par_metrics_[pit1];
1840                 y1 -= pm.descent();
1841                 // Save the paragraph position in the cache.
1842                 pm.setPosition(y1);
1843                 y1 -= pm.ascent();
1844         }
1845
1846         // Redo paragraphs below the anchor if necessary.
1847         int y2 = d->anchor_ypos_ + anchor_pm.descent();
1848         // We are now just below the anchor paragraph.
1849         pit_type pit2 = d->anchor_pit_ + 1;
1850         for (; pit2 < npit && y2 <= height_; ++pit2) {
1851                 tm.redoParagraph(pit2);
1852                 ParagraphMetrics & pm = tm.par_metrics_[pit2];
1853                 y2 += pm.ascent();
1854                 // Save the paragraph position in the cache.
1855                 pm.setPosition(y2);
1856                 y2 += pm.descent();
1857         }
1858
1859         LYXERR(Debug::PAINTING, "Metrics: "
1860                 << " anchor pit = " << d->anchor_pit_
1861                 << " anchor ypos = " << d->anchor_ypos_
1862                 << " y1 = " << y1
1863                 << " y2 = " << y2
1864                 << " pit1 = " << pit1
1865                 << " pit2 = " << pit2);
1866
1867         d->update_strategy_ = FullScreenUpdate;
1868
1869         if (lyxerr.debugging(Debug::WORKAREA)) {
1870                 LYXERR(Debug::WORKAREA, "BufferView::updateMetrics");
1871                 d->coord_cache_.dump();
1872         }
1873 }
1874
1875
1876 void BufferView::insertLyXFile(FileName const & fname)
1877 {
1878         BOOST_ASSERT(d->cursor_.inTexted());
1879
1880         // Get absolute path of file and add ".lyx"
1881         // to the filename if necessary
1882         FileName filename = fileSearch(string(), fname.absFilename(), "lyx");
1883
1884         docstring const disp_fn = makeDisplayPath(filename.absFilename());
1885         // emit message signal.
1886         message(bformat(_("Inserting document %1$s..."), disp_fn));
1887
1888         docstring res;
1889         Buffer buf("", false);
1890         if (buf.loadLyXFile(filename)) {
1891                 ErrorList & el = buffer_.errorList("Parse");
1892                 // Copy the inserted document error list into the current buffer one.
1893                 el = buf.errorList("Parse");
1894                 buffer_.undo().recordUndo(d->cursor_);
1895                 cap::pasteParagraphList(d->cursor_, buf.paragraphs(),
1896                                              buf.params().getTextClassPtr(), el);
1897                 res = _("Document %1$s inserted.");
1898         } else {
1899                 res = _("Could not insert document %1$s");
1900         }
1901
1902         updateMetrics();
1903         buffer_.changed();
1904         // emit message signal.
1905         message(bformat(res, disp_fn));
1906         buffer_.errors("Parse");
1907 }
1908
1909
1910 Point BufferView::coordOffset(DocIterator const & dit, bool boundary) const
1911 {
1912         int x = 0;
1913         int y = 0;
1914         int lastw = 0;
1915
1916         // Addup contribution of nested insets, from inside to outside,
1917         // keeping the outer paragraph for a special handling below
1918         for (size_t i = dit.depth() - 1; i >= 1; --i) {
1919                 CursorSlice const & sl = dit[i];
1920                 int xx = 0;
1921                 int yy = 0;
1922                 
1923                 // get relative position inside sl.inset()
1924                 sl.inset().cursorPos(*this, sl, boundary && (i + 1 == dit.depth()), xx, yy);
1925                 
1926                 // Make relative position inside of the edited inset relative to sl.inset()
1927                 x += xx;
1928                 y += yy;
1929                 
1930                 // In case of an RTL inset, the edited inset will be positioned to the left
1931                 // of xx:yy
1932                 if (sl.text()) {
1933                         bool boundary_i = boundary && i + 1 == dit.depth();
1934                         bool rtl = textMetrics(sl.text()).isRTL(sl, boundary_i);
1935                         if (rtl)
1936                                 x -= lastw;
1937                 }
1938
1939                 // remember width for the case that sl.inset() is positioned in an RTL inset
1940                 if (i && dit[i - 1].text()) {
1941                         // If this Inset is inside a Text Inset, retrieve the Dimension
1942                         // from the containing text instead of using Inset::dimension() which
1943                         // might not be implemented.
1944                         // FIXME (Abdel 23/09/2007): this is a bit messy because of the
1945                         // elimination of Inset::dim_ cache. This coordOffset() method needs
1946                         // to be rewritten in light of the new design.
1947                         Dimension const & dim = parMetrics(dit[i - 1].text(),
1948                                 dit[i - 1].pit()).insetDimension(&sl.inset());
1949                         lastw = dim.wid;
1950                 } else {
1951                         Dimension const dim = sl.inset().dimension(*this);
1952                         lastw = dim.wid;
1953                 }
1954                 
1955                 //lyxerr << "Cursor::getPos, i: "
1956                 // << i << " x: " << xx << " y: " << y << endl;
1957         }
1958
1959         // Add contribution of initial rows of outermost paragraph
1960         CursorSlice const & sl = dit[0];
1961         TextMetrics const & tm = textMetrics(sl.text());
1962         ParagraphMetrics const & pm = tm.parMetrics(sl.pit());
1963         BOOST_ASSERT(!pm.rows().empty());
1964         y -= pm.rows()[0].ascent();
1965 #if 1
1966         // FIXME: document this mess
1967         size_t rend;
1968         if (sl.pos() > 0 && dit.depth() == 1) {
1969                 int pos = sl.pos();
1970                 if (pos && boundary)
1971                         --pos;
1972 //              lyxerr << "coordOffset: boundary:" << boundary << " depth:" << dit.depth() << " pos:" << pos << " sl.pos:" << sl.pos() << endl;
1973                 rend = pm.pos2row(pos);
1974         } else
1975                 rend = pm.pos2row(sl.pos());
1976 #else
1977         size_t rend = pm.pos2row(sl.pos());
1978 #endif
1979         for (size_t rit = 0; rit != rend; ++rit)
1980                 y += pm.rows()[rit].height();
1981         y += pm.rows()[rend].ascent();
1982         
1983         TextMetrics const & bottom_tm = textMetrics(dit.bottom().text());
1984         
1985         // Make relative position from the nested inset now bufferview absolute.
1986         int xx = bottom_tm.cursorX(dit.bottom(), boundary && dit.depth() == 1);
1987         x += xx;
1988         
1989         // In the RTL case place the nested inset at the left of the cursor in 
1990         // the outer paragraph
1991         bool boundary_1 = boundary && 1 == dit.depth();
1992         bool rtl = bottom_tm.isRTL(dit.bottom(), boundary_1);
1993         if (rtl)
1994                 x -= lastw;
1995         
1996         return Point(x, y);
1997 }
1998
1999
2000 Point BufferView::getPos(DocIterator const & dit, bool boundary) const
2001 {
2002         CursorSlice const & bot = dit.bottom();
2003         TextMetrics const & tm = textMetrics(bot.text());
2004         if (!tm.has(bot.pit()))
2005                 return Point(-1, -1);
2006
2007         Point p = coordOffset(dit, boundary); // offset from outer paragraph
2008         p.y_ += tm.parMetrics(bot.pit()).position();
2009         return p;
2010 }
2011
2012
2013 void BufferView::draw(frontend::Painter & pain)
2014 {
2015         LYXERR(Debug::PAINTING, "\t\t*** START DRAWING ***");
2016         Text & text = buffer_.text();
2017         TextMetrics const & tm = d->text_metrics_[&text];
2018         int const y = tm.first().second->position();
2019         PainterInfo pi(this, pain);
2020
2021         switch (d->update_strategy_) {
2022
2023         case NoScreenUpdate:
2024                 // If no screen painting is actually needed, only some the different
2025                 // coordinates of insets and paragraphs needs to be updated.
2026                 pi.full_repaint = true;
2027                 pi.pain.setDrawingEnabled(false);
2028                 tm.draw(pi, 0, y);
2029                 break;
2030
2031         case SingleParUpdate:
2032                 pi.full_repaint = false;
2033                 // In general, only the current row of the outermost paragraph
2034                 // will be redrawn. Particular cases where selection spans
2035                 // multiple paragraph are correctly detected in TextMetrics.
2036                 tm.draw(pi, 0, y);
2037                 break;
2038
2039         case DecorationUpdate:
2040                 // FIXME: We should also distinguish DecorationUpdate to avoid text
2041                 // drawing if possible. This is not possible to do easily right now
2042                 // because of the single backing pixmap.
2043
2044         case FullScreenUpdate:
2045                 // The whole screen, including insets, will be refreshed.
2046                 pi.full_repaint = true;
2047
2048                 // Clear background.
2049                 pain.fillRectangle(0, 0, width_, height_,
2050                         buffer_.inset().backgroundColor());
2051
2052                 // Draw everything.
2053                 tm.draw(pi, 0, y);
2054
2055                 // and possibly grey out below
2056                 pair<pit_type, ParagraphMetrics const *> lastpm = tm.last();
2057                 int const y2 = lastpm.second->position() + lastpm.second->descent();
2058                 if (y2 < height_)
2059                         pain.fillRectangle(0, y2, width_, height_ - y2, Color_bottomarea);
2060                 break;
2061         }
2062         LYXERR(Debug::PAINTING, "\n\t\t*** END DRAWING  ***");
2063
2064         // The scrollbar needs an update.
2065         updateScrollbar();
2066
2067         // Normalize anchor for next time
2068         pair<pit_type, ParagraphMetrics const *> firstpm = tm.first();
2069         pair<pit_type, ParagraphMetrics const *> lastpm = tm.last();
2070         for (pit_type pit = firstpm.first; pit <= lastpm.first; ++pit) {
2071                 ParagraphMetrics const & pm = tm.parMetrics(pit);
2072                 if (pm.position() + pm.descent() > 0) {
2073                         d->anchor_pit_ = pit;
2074                         d->anchor_ypos_ = pm.position();
2075                         break;
2076                 }
2077         }
2078         LYXERR(Debug::PAINTING, "Found new anchor pit = " << d->anchor_pit_
2079                 << "  anchor ypos = " << d->anchor_ypos_);
2080 }
2081
2082
2083 void BufferView::message(docstring const & msg)
2084 {
2085         if (d->gui_)
2086                 d->gui_->message(msg);
2087 }
2088
2089
2090 void BufferView::showDialog(string const & name)
2091 {
2092         if (d->gui_)
2093                 d->gui_->showDialog(name, string());
2094 }
2095
2096
2097 void BufferView::showDialog(string const & name,
2098         string const & data, Inset * inset)
2099 {
2100         if (d->gui_)
2101                 d->gui_->showDialog(name, data, inset);
2102 }
2103
2104
2105 void BufferView::updateDialog(string const & name, string const & data)
2106 {
2107         if (d->gui_)
2108                 d->gui_->updateDialog(name, data);
2109 }
2110
2111
2112 void BufferView::setGuiDelegate(frontend::GuiBufferViewDelegate * gui)
2113 {
2114         d->gui_ = gui;
2115 }
2116
2117
2118 // FIXME: Move this out of BufferView again
2119 docstring BufferView::contentsOfPlaintextFile(FileName const & fname)
2120 {
2121         if (!fname.isReadableFile()) {
2122                 docstring const error = from_ascii(strerror(errno));
2123                 docstring const file = makeDisplayPath(fname.absFilename(), 50);
2124                 docstring const text =
2125                   bformat(_("Could not read the specified document\n"
2126                             "%1$s\ndue to the error: %2$s"), file, error);
2127                 Alert::error(_("Could not read file"), text);
2128                 return docstring();
2129         }
2130
2131         if (!fname.isReadableFile()) {
2132                 docstring const file = makeDisplayPath(fname.absFilename(), 50);
2133                 docstring const text =
2134                   bformat(_("%1$s\n is not readable."), file);
2135                 Alert::error(_("Could not open file"), text);
2136                 return docstring();
2137         }
2138
2139         // FIXME UNICODE: We don't know the encoding of the file
2140         docstring file_content = fname.fileContents("UTF-8");
2141         if (file_content.empty()) {
2142                 Alert::error(_("Reading not UTF-8 encoded file"),
2143                              _("The file is not UTF-8 encoded.\n"
2144                                "It will be read as local 8Bit-encoded.\n"
2145                                "If this does not give the correct result\n"
2146                                "then please change the encoding of the file\n"
2147                                "to UTF-8 with a program other than LyX.\n"));
2148                 file_content = fname.fileContents("local8bit");
2149         }
2150
2151         return normalize_c(file_content);
2152 }
2153
2154
2155 void BufferView::insertPlaintextFile(FileName const & f, bool asParagraph)
2156 {
2157         docstring const tmpstr = contentsOfPlaintextFile(f);
2158
2159         if (tmpstr.empty())
2160                 return;
2161
2162         Cursor & cur = cursor();
2163         cap::replaceSelection(cur);
2164         buffer_.undo().recordUndo(cur);
2165         if (asParagraph)
2166                 cur.innerText()->insertStringAsParagraphs(cur, tmpstr);
2167         else
2168                 cur.innerText()->insertStringAsLines(cur, tmpstr);
2169
2170         updateMetrics();
2171         buffer_.changed();
2172 }
2173
2174
2175 docstring const & BufferView::inlineCompletion() const
2176 {
2177         return d->inlineCompletion;
2178 }
2179
2180
2181 size_t const & BufferView::inlineCompletionUniqueChars() const
2182 {
2183         return d->inlineCompletionUniqueChars;
2184 }
2185
2186
2187 DocIterator const & BufferView::inlineCompletionPos() const
2188 {
2189         return d->inlineCompletionPos;
2190 }
2191
2192
2193 bool samePar(DocIterator const & a, DocIterator const & b)
2194 {
2195         if (a.empty() && b.empty())
2196                 return true;
2197         if (a.empty() || b.empty())
2198                 return false;
2199         return &a.innerParagraph() == &b.innerParagraph();
2200 }
2201
2202
2203 void BufferView::setInlineCompletion(Cursor & cur, DocIterator const & pos, 
2204         docstring const & completion, size_t uniqueChars)
2205 {
2206         uniqueChars = min(completion.size(), uniqueChars);
2207         bool changed = d->inlineCompletion != completion
2208                 || d->inlineCompletionUniqueChars != uniqueChars;
2209         bool singlePar = true;
2210         d->inlineCompletion = completion;
2211         d->inlineCompletionUniqueChars = min(completion.size(), uniqueChars);
2212         
2213         lyxerr << "setInlineCompletion pos=" << pos << " completion=" << completion << " uniqueChars=" << uniqueChars << std::endl;
2214         
2215         // at new position?
2216         DocIterator const & old = d->inlineCompletionPos;
2217         if (old != pos) {
2218                 lyxerr << "inlineCompletionPos changed" << std::endl;
2219                 // old or pos are in another paragraph?
2220                 if ((!samePar(cur, pos) && !pos.empty())
2221                     || (!samePar(cur, old) && !old.empty())) {
2222                         singlePar = false;
2223                         lyxerr << "different paragraph" << std::endl;
2224                 }
2225                 d->inlineCompletionPos = pos;
2226         }
2227         
2228         // set update flags
2229         if (changed) {
2230                 lyxerr << "inlineCompletion changed" << std::endl;
2231                 
2232                 Update::flags flags
2233                 = cur.disp_.update() | Update::Force;
2234                 if (singlePar && !(flags | Update::SinglePar))
2235                     flags = flags | Update::SinglePar;
2236                 cur.updateFlags(flags);
2237         }
2238 }
2239
2240 } // namespace lyx