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