]> git.lyx.org Git - lyx.git/blob - src/BufferView.cpp
6a1e25e6922b19c2d0582b92cbeb308f0c54b25c
[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 "BranchList.h"
20 #include "Buffer.h"
21 #include "buffer_funcs.h"
22 #include "BufferList.h"
23 #include "BufferParams.h"
24 #include "CoordCache.h"
25 #include "Cursor.h"
26 #include "CutAndPaste.h"
27 #include "DispatchResult.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 "LayoutFile.h"
38 #include "Lexer.h"
39 #include "LyX.h"
40 #include "LyXAction.h"
41 #include "lyxfind.h"
42 #include "Layout.h"
43 #include "LyXRC.h"
44 #include "MetricsInfo.h"
45 #include "Paragraph.h"
46 #include "ParagraphParameters.h"
47 #include "ParIterator.h"
48 #include "Session.h"
49 #include "Text.h"
50 #include "TextClass.h"
51 #include "TextMetrics.h"
52 #include "TexRow.h"
53 #include "TocBackend.h"
54 #include "VSpace.h"
55 #include "WordLangTuple.h"
56
57 #include "insets/InsetBibtex.h"
58 #include "insets/InsetCommand.h" // ChangeRefs
59 #include "insets/InsetExternal.h"
60 #include "insets/InsetGraphics.h"
61 #include "insets/InsetRef.h"
62 #include "insets/InsetText.h"
63 #include "insets/InsetNote.h"
64
65 #include "frontends/alert.h"
66 #include "frontends/Application.h"
67 #include "frontends/Delegates.h"
68 #include "frontends/FontMetrics.h"
69 #include "frontends/Painter.h"
70 #include "frontends/Selection.h"
71
72 #include "graphics/Previews.h"
73
74 #include "support/convert.h"
75 #include "support/debug.h"
76 #include "support/ExceptionMessage.h"
77 #include "support/filetools.h"
78 #include "support/gettext.h"
79 #include "support/lstrings.h"
80 #include "support/Package.h"
81 #include "support/types.h"
82
83 #include <cerrno>
84 #include <fstream>
85 #include <functional>
86 #include <iterator>
87 #include <sstream>
88 #include <vector>
89
90 using namespace std;
91 using namespace lyx::support;
92
93 namespace lyx {
94
95 namespace Alert = frontend::Alert;
96
97 namespace {
98
99 /// Return an inset of this class if it exists at the current cursor position
100 template <class T>
101 T * getInsetByCode(Cursor const & cur, InsetCode code)
102 {
103         DocIterator it = cur;
104         Inset * inset = it.nextInset();
105         if (inset && inset->lyxCode() == code)
106                 return static_cast<T*>(inset);
107         return 0;
108 }
109
110
111 bool findInset(DocIterator & dit, vector<InsetCode> const & codes,
112         bool same_content);
113
114 bool findNextInset(DocIterator & dit, vector<InsetCode> const & codes,
115         docstring const & contents)
116 {
117         DocIterator tmpdit = dit;
118
119         while (tmpdit) {
120                 Inset const * inset = tmpdit.nextInset();
121                 if (inset
122                     && std::find(codes.begin(), codes.end(), inset->lyxCode()) != codes.end()
123                     && (contents.empty() ||
124                     static_cast<InsetCommand const *>(inset)->getFirstNonOptParam() == contents)) {
125                         dit = tmpdit;
126                         return true;
127                 }
128                 tmpdit.forwardInset();
129         }
130
131         return false;
132 }
133
134
135 /// Looks for next inset with one of the given codes.
136 bool findInset(DocIterator & dit, vector<InsetCode> const & codes,
137         bool same_content)
138 {
139         docstring contents;
140         DocIterator tmpdit = dit;
141         tmpdit.forwardInset();
142         if (!tmpdit)
143                 return false;
144
145         if (same_content) {
146                 Inset const * inset = tmpdit.nextInset();
147                 if (inset
148                     && std::find(codes.begin(), codes.end(), inset->lyxCode()) != codes.end()) {
149                         contents = static_cast<InsetCommand const *>(inset)->getFirstNonOptParam();
150                 }
151         }
152
153         if (!findNextInset(tmpdit, codes, contents)) {
154                 if (dit.depth() != 1 || dit.pit() != 0 || dit.pos() != 0) {
155                         Inset * inset = &tmpdit.bottom().inset();
156                         tmpdit = doc_iterator_begin(&inset->buffer(), inset);
157                         if (!findNextInset(tmpdit, codes, contents))
158                                 return false;
159                 } else {
160                         return false;
161                 }
162         }
163
164         dit = tmpdit;
165         return true;
166 }
167
168
169 /// Looks for next inset with the given code
170 void findInset(DocIterator & dit, InsetCode code, bool same_content)
171 {
172         findInset(dit, vector<InsetCode>(1, code), same_content);
173 }
174
175
176 /// Moves cursor to the next inset with one of the given codes.
177 void gotoInset(BufferView * bv, vector<InsetCode> const & codes,
178                bool same_content)
179 {
180         Cursor tmpcur = bv->cursor();
181         if (!findInset(tmpcur, codes, same_content)) {
182                 bv->cursor().message(_("No more insets"));
183                 return;
184         }
185
186         tmpcur.clearSelection();
187         bv->setCursor(tmpcur);
188         bv->showCursor();
189 }
190
191
192 /// Moves cursor to the next inset with given code.
193 void gotoInset(BufferView * bv, InsetCode code, bool same_content)
194 {
195         gotoInset(bv, vector<InsetCode>(1, code), same_content);
196 }
197
198
199 /// A map from a Text to the associated text metrics
200 typedef map<Text const *, TextMetrics> TextMetricsCache;
201
202 enum ScreenUpdateStrategy {
203         NoScreenUpdate,
204         SingleParUpdate,
205         FullScreenUpdate,
206         DecorationUpdate
207 };
208
209 } // anon namespace
210
211
212 /////////////////////////////////////////////////////////////////////
213 //
214 // BufferView
215 //
216 /////////////////////////////////////////////////////////////////////
217
218 struct BufferView::Private
219 {
220         Private(BufferView & bv): wh_(0), cursor_(bv),
221                 anchor_pit_(0), anchor_ypos_(0),
222                 inlineCompletionUniqueChars_(0),
223                 last_inset_(0), mouse_position_cache_(),
224                 bookmark_edit_position_(0), gui_(0)
225         {}
226
227         ///
228         ScrollbarParameters scrollbarParameters_;
229         ///
230         ScreenUpdateStrategy update_strategy_;
231         ///
232         CoordCache coord_cache_;
233
234         /// Estimated average par height for scrollbar.
235         int wh_;
236         /// this is used to handle XSelection events in the right manner.
237         struct {
238                 CursorSlice cursor;
239                 CursorSlice anchor;
240                 bool set;
241         } xsel_cache_;
242         ///
243         Cursor cursor_;
244         ///
245         pit_type anchor_pit_;
246         ///
247         int anchor_ypos_;
248         ///
249         vector<int> par_height_;
250
251         ///
252         DocIterator inlineCompletionPos_;
253         ///
254         docstring inlineCompletion_;
255         ///
256         size_t inlineCompletionUniqueChars_;
257
258         /// keyboard mapping object.
259         Intl intl_;
260
261         /// last visited inset.
262         /** kept to send setMouseHover(false).
263           * Not owned, so don't delete.
264           */
265         Inset * last_inset_;
266
267         /// position of the mouse at the time of the last mouse move
268         /// This is used to update the hovering status of inset in
269         /// cases where the buffer is scrolled, but the mouse didn't move.
270         Point mouse_position_cache_;
271
272         // cache for id of the paragraph which was edited the last time
273         int bookmark_edit_position_;
274
275         mutable TextMetricsCache text_metrics_;
276
277         /// Whom to notify.
278         /** Not owned, so don't delete.
279           */
280         frontend::GuiBufferViewDelegate * gui_;
281
282         /// Cache for Find Next
283         FuncRequest search_request_cache_;
284
285         ///
286         map<string, Inset *> edited_insets_;
287 };
288
289
290 BufferView::BufferView(Buffer & buf)
291         : width_(0), height_(0), full_screen_(false), buffer_(buf),
292       d(new Private(*this))
293 {
294         d->xsel_cache_.set = false;
295         d->intl_.initKeyMapper(lyxrc.use_kbmap);
296
297         d->cursor_.setBuffer(&buf);
298         d->cursor_.push(buffer_.inset());
299         d->cursor_.resetAnchor();
300         d->cursor_.setCurrentFont();
301
302         if (graphics::Previews::status() != LyXRC::PREVIEW_OFF)
303                 thePreviews().generateBufferPreviews(buffer_);
304 }
305
306
307 BufferView::~BufferView()
308 {
309         // current buffer is going to be switched-off, save cursor pos
310         // Ideally, the whole cursor stack should be saved, but session
311         // currently can only handle bottom (whole document) level pit and pos.
312         // That is to say, if a cursor is in a nested inset, it will be
313         // restore to the left of the top level inset.
314         LastFilePosSection::FilePos fp;
315         fp.pit = d->cursor_.bottom().pit();
316         fp.pos = d->cursor_.bottom().pos();
317         theSession().lastFilePos().save(buffer_.fileName(), fp);
318
319         delete d;
320 }
321
322
323 int BufferView::rightMargin() const
324 {
325         // The additional test for the case the outliner is opened.
326         if (!full_screen_ ||
327                 !lyxrc.full_screen_limit ||
328                 width_ < lyxrc.full_screen_width + 20)
329                         return 10;
330
331         return (width_ - lyxrc.full_screen_width) / 2;
332 }
333
334
335 int BufferView::leftMargin() const
336 {
337         return rightMargin();
338 }
339
340
341 bool BufferView::isTopScreen() const
342 {
343         return d->scrollbarParameters_.position == d->scrollbarParameters_.min;
344 }
345
346
347 bool BufferView::isBottomScreen() const
348 {
349         return d->scrollbarParameters_.position == d->scrollbarParameters_.max;
350 }
351
352
353 Intl & BufferView::getIntl()
354 {
355         return d->intl_;
356 }
357
358
359 Intl const & BufferView::getIntl() const
360 {
361         return d->intl_;
362 }
363
364
365 CoordCache & BufferView::coordCache()
366 {
367         return d->coord_cache_;
368 }
369
370
371 CoordCache const & BufferView::coordCache() const
372 {
373         return d->coord_cache_;
374 }
375
376
377 Buffer & BufferView::buffer()
378 {
379         return buffer_;
380 }
381
382
383 Buffer const & BufferView::buffer() const
384 {
385         return buffer_;
386 }
387
388
389 bool BufferView::fitCursor()
390 {
391         if (cursorStatus(d->cursor_) == CUR_INSIDE) {
392                 frontend::FontMetrics const & fm =
393                         theFontMetrics(d->cursor_.getFont().fontInfo());
394                 int const asc = fm.maxAscent();
395                 int const des = fm.maxDescent();
396                 Point const p = getPos(d->cursor_, d->cursor_.boundary());
397                 if (p.y_ - asc >= 0 && p.y_ + des < height_)
398                         return false;
399         }
400         return true;
401 }
402
403
404 void BufferView::processUpdateFlags(Update::flags flags)
405 {
406         // This is close to a hot-path.
407         LYXERR(Debug::DEBUG, "BufferView::processUpdateFlags()"
408                 << "[fitcursor = " << (flags & Update::FitCursor)
409                 << ", forceupdate = " << (flags & Update::Force)
410                 << ", singlepar = " << (flags & Update::SinglePar)
411                 << "]  buffer: " << &buffer_);
412
413         buffer_.updateMacros();
414
415         // Now do the first drawing step if needed. This consists on updating
416         // the CoordCache in updateMetrics().
417         // The second drawing step is done in WorkArea::redraw() if needed.
418
419         // Case when no explicit update is requested.
420         if (!flags) {
421                 // no need to redraw anything.
422                 d->update_strategy_ = NoScreenUpdate;
423                 return;
424         }
425
426         if (flags == Update::Decoration) {
427                 d->update_strategy_ = DecorationUpdate;
428                 buffer_.changed(false);
429                 return;
430         }
431
432         if (flags == Update::FitCursor
433                 || flags == (Update::Decoration | Update::FitCursor)) {
434                 // tell the frontend to update the screen if needed.
435                 if (fitCursor()) {
436                         showCursor();
437                         return;
438                 }
439                 if (flags & Update::Decoration) {
440                         d->update_strategy_ = DecorationUpdate;
441                         buffer_.changed(false);
442                         return;
443                 }
444                 // no screen update is needed.
445                 d->update_strategy_ = NoScreenUpdate;
446                 return;
447         }
448
449         bool const full_metrics = flags & Update::Force || !singleParUpdate();
450
451         if (full_metrics)
452                 // We have to update the full screen metrics.
453                 updateMetrics();
454
455         if (!(flags & Update::FitCursor)) {
456                 // Nothing to do anymore. Trigger a redraw and return
457                 buffer_.changed(false);
458                 return;
459         }
460
461         // updateMetrics() does not update paragraph position
462         // This is done at draw() time. So we need a redraw!
463         buffer_.changed(false);
464
465         if (fitCursor()) {
466                 // The cursor is off screen so ensure it is visible.
467                 // refresh it:
468                 showCursor();
469         }
470
471         updateHoveredInset();
472 }
473
474
475 void BufferView::updateScrollbar()
476 {
477         if (height_ == 0 && width_ == 0)
478                 return;
479
480         // We prefer fixed size line scrolling.
481         d->scrollbarParameters_.single_step = defaultRowHeight();
482         // We prefer full screen page scrolling.
483         d->scrollbarParameters_.page_step = height_;
484
485         Text & t = buffer_.text();
486         TextMetrics & tm = d->text_metrics_[&t];                
487
488         LYXERR(Debug::GUI, " Updating scrollbar: height: "
489                 << t.paragraphs().size()
490                 << " curr par: " << d->cursor_.bottom().pit()
491                 << " default height " << defaultRowHeight());
492
493         size_t const parsize = t.paragraphs().size();
494         if (d->par_height_.size() != parsize) {
495                 d->par_height_.clear();
496                 // FIXME: We assume a default paragraph height of 2 rows. This
497                 // should probably be pondered with the screen width.
498                 d->par_height_.resize(parsize, defaultRowHeight() * 2);
499         }
500
501         // Look at paragraph heights on-screen
502         pair<pit_type, ParagraphMetrics const *> first = tm.first();
503         pair<pit_type, ParagraphMetrics const *> last = tm.last();
504         for (pit_type pit = first.first; pit <= last.first; ++pit) {
505                 d->par_height_[pit] = tm.parMetrics(pit).height();
506                 LYXERR(Debug::SCROLLING, "storing height for pit " << pit << " : "
507                         << d->par_height_[pit]);
508         }
509
510         int top_pos = first.second->position() - first.second->ascent();
511         int bottom_pos = last.second->position() + last.second->descent();
512         bool first_visible = first.first == 0 && top_pos >= 0;
513         bool last_visible = last.first + 1 == int(parsize) && bottom_pos <= height_;
514         if (first_visible && last_visible) {
515                 d->scrollbarParameters_.min = 0;
516                 d->scrollbarParameters_.max = 0;
517                 return;
518         }
519
520         d->scrollbarParameters_.min = top_pos;
521         for (size_t i = 0; i != size_t(first.first); ++i)
522                 d->scrollbarParameters_.min -= d->par_height_[i];
523         d->scrollbarParameters_.max = bottom_pos;
524         for (size_t i = last.first + 1; i != parsize; ++i)
525                 d->scrollbarParameters_.max += d->par_height_[i];
526
527         d->scrollbarParameters_.position = 0;
528         // The reference is the top position so we remove one page.
529         if (lyxrc.scroll_below_document)
530                 d->scrollbarParameters_.max -= minVisiblePart();
531         else
532                 d->scrollbarParameters_.max -= d->scrollbarParameters_.page_step;
533 }
534
535
536 ScrollbarParameters const & BufferView::scrollbarParameters() const
537 {
538         return d->scrollbarParameters_;
539 }
540
541
542 docstring BufferView::toolTip(int x, int y) const
543 {
544         // Get inset under mouse, if there is one.
545         Inset const * covering_inset = getCoveringInset(buffer_.text(), x, y);
546         if (!covering_inset)
547                 // No inset, no tooltip...
548                 return docstring();
549         return covering_inset->toolTip(*this, x, y);
550 }
551
552
553 docstring BufferView::contextMenu(int x, int y) const
554 {
555         //If there is a selection, return the containing inset menu
556         if (d->cursor_.selection())
557                 return d->cursor_.inset().contextMenu(*this, x, y);
558
559         // Get inset under mouse, if there is one.
560         Inset const * covering_inset = getCoveringInset(buffer_.text(), x, y);
561         if (covering_inset)
562                 return covering_inset->contextMenu(*this, x, y);
563
564         return buffer_.inset().contextMenu(*this, x, y);
565 }
566
567
568 void BufferView::scrollDocView(int value)
569 {
570         int const offset = value - d->scrollbarParameters_.position;
571
572         // No scrolling at all? No need to redraw anything
573         if (offset == 0)
574                 return;
575
576         // If the offset is less than 2 screen height, prefer to scroll instead.
577         if (abs(offset) <= 2 * height_) {
578                 d->anchor_ypos_ -= offset;
579                 buffer_.changed(true);
580                 updateHoveredInset();
581                 return;
582         }
583
584         // cut off at the top
585         if (value <= d->scrollbarParameters_.min) {
586                 DocIterator dit = doc_iterator_begin(&buffer_);
587                 showCursor(dit);
588                 LYXERR(Debug::SCROLLING, "scroll to top");
589                 return;
590         }
591
592         // cut off at the bottom
593         if (value >= d->scrollbarParameters_.max) {
594                 DocIterator dit = doc_iterator_end(&buffer_);
595                 dit.backwardPos();
596                 showCursor(dit);
597                 LYXERR(Debug::SCROLLING, "scroll to bottom");
598                 return;
599         }
600
601         // find paragraph at target position
602         int par_pos = d->scrollbarParameters_.min;
603         pit_type i = 0;
604         for (; i != int(d->par_height_.size()); ++i) {
605                 par_pos += d->par_height_[i];
606                 if (par_pos >= value)
607                         break;
608         }
609
610         if (par_pos < value) {
611                 // It seems we didn't find the correct pit so stay on the safe side and
612                 // scroll to bottom.
613                 LYXERR0("scrolling position not found!");
614                 scrollDocView(d->scrollbarParameters_.max);
615                 return;
616         }
617
618         DocIterator dit = doc_iterator_begin(&buffer_);
619         dit.pit() = i;
620         LYXERR(Debug::SCROLLING, "value = " << value << " -> scroll to pit " << i);
621         showCursor(dit);
622 }
623
624
625 // FIXME: this method is not working well.
626 void BufferView::setCursorFromScrollbar()
627 {
628         TextMetrics & tm = d->text_metrics_[&buffer_.text()];
629
630         int const height = 2 * defaultRowHeight();
631         int const first = height;
632         int const last = height_ - height;
633         int newy = 0;
634         Cursor const & oldcur = d->cursor_;
635
636         switch (cursorStatus(oldcur)) {
637         case CUR_ABOVE:
638                 newy = first;
639                 break;
640         case CUR_BELOW:
641                 newy = last;
642                 break;
643         case CUR_INSIDE:
644                 int const y = getPos(oldcur, oldcur.boundary()).y_;
645                 newy = min(last, max(y, first));
646                 if (y == newy) 
647                         return;
648         }
649         // We reset the cursor because cursorStatus() does not
650         // work when the cursor is within mathed.
651         Cursor cur(*this);
652         cur.reset();
653         tm.setCursorFromCoordinates(cur, 0, newy);
654
655         // update the bufferview cursor and notify insets
656         // FIXME: Care about the d->cursor_ flags to redraw if needed
657         Cursor old = d->cursor_;
658         mouseSetCursor(cur);
659         bool badcursor = notifyCursorLeavesOrEnters(old, d->cursor_);
660         if (badcursor)
661                 d->cursor_.fixIfBroken();
662 }
663
664
665 Change const BufferView::getCurrentChange() const
666 {
667         if (!d->cursor_.selection())
668                 return Change(Change::UNCHANGED);
669
670         DocIterator dit = d->cursor_.selectionBegin();
671         return dit.paragraph().lookupChange(dit.pos());
672 }
673
674
675 // this could be used elsewhere as well?
676 // FIXME: This does not work within mathed!
677 CursorStatus BufferView::cursorStatus(DocIterator const & dit) const
678 {
679         Point const p = getPos(dit, dit.boundary());
680         if (p.y_ < 0)
681                 return CUR_ABOVE;
682         if (p.y_ > workHeight())
683                 return CUR_BELOW;
684         return CUR_INSIDE;
685 }
686
687
688 void BufferView::bookmarkEditPosition()
689 {
690         // Don't eat cpu time for each keystroke
691         if (d->cursor_.paragraph().id() == d->bookmark_edit_position_)
692                 return;
693         saveBookmark(0);
694         d->bookmark_edit_position_ = d->cursor_.paragraph().id();
695 }
696
697
698 void BufferView::saveBookmark(unsigned int idx)
699 {
700         // tentatively save bookmark, id and pos will be used to
701         // acturately locate a bookmark in a 'live' lyx session.
702         // pit and pos will be updated with bottom level pit/pos
703         // when lyx exits.
704         if (!buffer_.isInternal()) {
705                 theSession().bookmarks().save(
706                         buffer_.fileName(),
707                         d->cursor_.bottom().pit(),
708                         d->cursor_.bottom().pos(),
709                         d->cursor_.paragraph().id(),
710                         d->cursor_.pos(),
711                         idx
712                         );
713                 if (idx)
714                         // emit message signal.
715                         message(_("Save bookmark"));
716         }
717 }
718
719
720 bool BufferView::moveToPosition(pit_type bottom_pit, pos_type bottom_pos,
721         int top_id, pos_type top_pos)
722 {
723         bool success = false;
724         DocIterator dit;
725
726         d->cursor_.clearSelection();
727
728         // if a valid par_id is given, try it first
729         // This is the case for a 'live' bookmark when unique paragraph ID
730         // is used to track bookmarks.
731         if (top_id > 0) {
732                 dit = buffer_.getParFromID(top_id);
733                 if (!dit.atEnd()) {
734                         dit.pos() = min(dit.paragraph().size(), top_pos);
735                         // Some slices of the iterator may not be
736                         // reachable (e.g. closed collapsable inset)
737                         // so the dociterator may need to be
738                         // shortened. Otherwise, setCursor may crash
739                         // lyx when the cursor can not be set to these
740                         // insets.
741                         size_t const n = dit.depth();
742                         for (size_t i = 0; i < n; ++i)
743                                 if (!dit[i].inset().editable()) {
744                                         dit.resize(i);
745                                         break;
746                                 }
747                         success = true;
748                 }
749         }
750
751         // if top_id == 0, or searching through top_id failed
752         // This is the case for a 'restored' bookmark when only bottom
753         // (document level) pit was saved. Because of this, bookmark
754         // restoration is inaccurate. If a bookmark was within an inset,
755         // it will be restored to the left of the outmost inset that contains
756         // the bookmark.
757         if (bottom_pit < int(buffer_.paragraphs().size())) {
758                 dit = doc_iterator_begin(&buffer_);
759                                 
760                 dit.pit() = bottom_pit;
761                 dit.pos() = min(bottom_pos, dit.paragraph().size());
762                 success = true;
763         }
764
765         if (success) {
766                 // Note: only bottom (document) level pit is set.
767                 setCursor(dit);
768                 // set the current font.
769                 d->cursor_.setCurrentFont();
770                 // To center the screen on this new position we need the
771                 // paragraph position which is computed at draw() time.
772                 // So we need a redraw!
773                 buffer_.changed(false);
774                 if (fitCursor())
775                         showCursor();
776         }
777
778         return success;
779 }
780
781
782 void BufferView::translateAndInsert(char_type c, Text * t, Cursor & cur)
783 {
784         if (lyxrc.rtl_support) {
785                 if (d->cursor_.real_current_font.isRightToLeft()) {
786                         if (d->intl_.keymap == Intl::PRIMARY)
787                                 d->intl_.keyMapSec();
788                 } else {
789                         if (d->intl_.keymap == Intl::SECONDARY)
790                                 d->intl_.keyMapPrim();
791                 }
792         }
793
794         d->intl_.getTransManager().translateAndInsert(c, t, cur);
795 }
796
797
798 int BufferView::workWidth() const
799 {
800         return width_;
801 }
802
803
804 void BufferView::recenter()
805 {
806         showCursor(d->cursor_, true);
807 }
808
809
810 void BufferView::showCursor()
811 {
812         showCursor(d->cursor_, false);
813 }
814
815
816 void BufferView::showCursor(DocIterator const & dit, bool recenter)
817 {
818         if (scrollToCursor(dit, recenter)) {
819                 buffer_.changed(false);
820                 updateHoveredInset();
821         }
822 }
823
824
825 void BufferView::scrollToCursor()
826 {
827         if (scrollToCursor(d->cursor_, false))
828                 updateHoveredInset();
829 }
830
831
832 bool BufferView::scrollToCursor(DocIterator const & dit, bool recenter)
833 {
834         // We are not properly started yet, delay until resizing is
835         // done.
836         if (height_ == 0)
837                 return false;
838
839         LYXERR(Debug::SCROLLING, "recentering!");
840
841         CursorSlice const & bot = dit.bottom();
842         TextMetrics & tm = d->text_metrics_[bot.text()];
843
844         pos_type const max_pit = pos_type(bot.text()->paragraphs().size() - 1);
845         int bot_pit = bot.pit();
846         if (bot_pit > max_pit) {
847                 // FIXME: Why does this happen?
848                 LYXERR0("bottom pit is greater that max pit: "
849                         << bot_pit << " > " << max_pit);
850                 bot_pit = max_pit;
851         }
852
853         if (bot_pit == tm.first().first - 1)
854                 tm.newParMetricsUp();
855         else if (bot_pit == tm.last().first + 1)
856                 tm.newParMetricsDown();
857
858         if (tm.contains(bot_pit)) {
859                 ParagraphMetrics const & pm = tm.parMetrics(bot_pit);
860                 LASSERT(!pm.rows().empty(), /**/);
861                 // FIXME: smooth scrolling doesn't work in mathed.
862                 CursorSlice const & cs = dit.innerTextSlice();
863                 int offset = coordOffset(dit, dit.boundary()).y_;
864                 int ypos = pm.position() + offset;
865                 Dimension const & row_dim =
866                         pm.getRow(cs.pos(), dit.boundary()).dimension();
867                 int scrolled = 0;
868                 if (recenter)
869                         scrolled = scroll(ypos - height_/2);
870                 else if (ypos - row_dim.ascent() < 0)
871                         scrolled = scrollUp(- ypos + row_dim.ascent());
872                 else if (ypos + row_dim.descent() > height_)
873                         scrolled = scrollDown(ypos - height_ + defaultRowHeight() ); 
874
875                 // else, nothing to do, the cursor is already visible so we just return.
876                 if (scrolled != 0) {
877                         updateMetrics();
878                         return true;
879                 }
880                 return false;
881         }
882
883         // fix inline completion position
884         if (d->inlineCompletionPos_.fixIfBroken())
885                 d->inlineCompletionPos_ = DocIterator();
886
887         tm.redoParagraph(bot_pit);
888         ParagraphMetrics const & pm = tm.parMetrics(bot_pit);
889         int offset = coordOffset(dit, dit.boundary()).y_;
890
891         d->anchor_pit_ = bot_pit;
892         CursorSlice const & cs = dit.innerTextSlice();
893         Dimension const & row_dim =
894                 pm.getRow(cs.pos(), dit.boundary()).dimension();
895
896         if (recenter)
897                 d->anchor_ypos_ = height_/2;
898         else if (d->anchor_pit_ == 0)
899                 d->anchor_ypos_ = offset + pm.ascent();
900         else if (d->anchor_pit_ == max_pit)
901                 d->anchor_ypos_ = height_ - offset - row_dim.descent();
902         else if (offset > height_)
903                 d->anchor_ypos_ = height_ - offset - defaultRowHeight();
904         else
905                 d->anchor_ypos_ = defaultRowHeight() * 2;
906
907         updateMetrics();
908         return true;
909 }
910
911
912 void BufferView::updateDocumentClass(DocumentClass const * const olddc)
913 {
914         message(_("Converting document to new document class..."));
915         
916         StableDocIterator backcur(d->cursor_);
917         ErrorList & el = buffer_.errorList("Class Switch");
918         cap::switchBetweenClasses(
919                         olddc, buffer_.params().documentClassPtr(),
920                         static_cast<InsetText &>(buffer_.inset()), el);
921
922         setCursor(backcur.asDocIterator(&buffer_));
923
924         buffer_.errors("Class Switch");
925         buffer_.updateBuffer();
926 }
927
928 /** Return the change status at cursor position, taking in account the
929  * status at each level of the document iterator (a table in a deleted
930  * footnote is deleted).
931  * When \param outer is true, the top slice is not looked at.
932  */
933 static Change::Type lookupChangeType(DocIterator const & dit, bool outer = false)
934 {
935         size_t const depth = dit.depth() - (outer ? 1 : 0);
936
937         for (size_t i = 0 ; i < depth ; ++i) {
938                 CursorSlice const & slice = dit[i];
939                 if (!slice.inset().inMathed()
940                     && slice.pos() < slice.paragraph().size()) {
941                         Change::Type const ch = slice.paragraph().lookupChange(slice.pos()).type;
942                         if (ch != Change::UNCHANGED)
943                                 return ch;
944                 }
945         }
946         return Change::UNCHANGED;
947 }
948
949
950 bool BufferView::getStatus(FuncRequest const & cmd, FuncStatus & flag)
951 {
952         // Can we use a readonly buffer?
953         if (buffer_.isReadonly()
954             && !lyxaction.funcHasFlag(cmd.action, LyXAction::ReadOnly)
955             && !lyxaction.funcHasFlag(cmd.action, LyXAction::NoBuffer)) {
956                 flag.message(from_utf8(N_("Document is read-only")));
957                 flag.setEnabled(false);
958                 return true;
959         }
960         // Are we in a DELETED change-tracking region?
961         if (lookupChangeType(d->cursor_, true) == Change::DELETED
962             && !lyxaction.funcHasFlag(cmd.action, LyXAction::ReadOnly)
963             && !lyxaction.funcHasFlag(cmd.action, LyXAction::NoBuffer)) {
964                 flag.message(from_utf8(N_("This portion of the document is deleted.")));
965                 flag.setEnabled(false);
966                 return true;
967         }
968
969         Cursor & cur = d->cursor_;
970
971         if (cur.getStatus(cmd, flag))
972                 return true;
973
974         switch (cmd.action) {
975
976         // FIXME: This is a bit problematic because we don't check is this is a
977         // document BufferView or not for these LFUNs. We probably have to
978         // dispatch both to currentBufferView() and, if that fails,
979         // to documentBufferView(); same as we do know for current Buffer and
980         // document Buffer. Ideally those LFUN should go to Buffer as they*
981         // operate on the full Buffer and the cursor is only needed either for
982         // an Undo record or to restore a cursor position. But we don't know
983         // how to do that inside Buffer of course.
984         case LFUN_BUFFER_PARAMS_APPLY:
985         case LFUN_LAYOUT_MODULES_CLEAR:
986         case LFUN_LAYOUT_MODULE_ADD:
987         case LFUN_LAYOUT_RELOAD:
988         case LFUN_TEXTCLASS_APPLY:
989         case LFUN_TEXTCLASS_LOAD:
990                 flag.setEnabled(!buffer_.isReadonly());
991                 break;
992
993         case LFUN_UNDO:
994                 flag.setEnabled(buffer_.undo().hasUndoStack());
995                 break;
996         case LFUN_REDO:
997                 flag.setEnabled(buffer_.undo().hasRedoStack());
998                 break;
999         case LFUN_FILE_INSERT:
1000         case LFUN_FILE_INSERT_PLAINTEXT_PARA:
1001         case LFUN_FILE_INSERT_PLAINTEXT:
1002         case LFUN_BOOKMARK_SAVE:
1003                 // FIXME: Actually, these LFUNS should be moved to Text
1004                 flag.setEnabled(cur.inTexted());
1005                 break;
1006
1007         case LFUN_FONT_STATE:
1008         case LFUN_LABEL_INSERT:
1009         case LFUN_INFO_INSERT:
1010         case LFUN_INSET_EDIT:
1011         case LFUN_PARAGRAPH_GOTO:
1012         case LFUN_NOTE_NEXT:
1013         case LFUN_REFERENCE_NEXT:
1014         case LFUN_WORD_FIND:
1015         case LFUN_WORD_FIND_FORWARD:
1016         case LFUN_WORD_FIND_BACKWARD:
1017         case LFUN_WORD_FINDADV:
1018         case LFUN_WORD_REPLACE:
1019         case LFUN_MARK_OFF:
1020         case LFUN_MARK_ON:
1021         case LFUN_MARK_TOGGLE:
1022         case LFUN_SCREEN_RECENTER:
1023         case LFUN_SCREEN_SHOW_CURSOR:
1024         case LFUN_BIBTEX_DATABASE_ADD:
1025         case LFUN_BIBTEX_DATABASE_DEL:
1026         case LFUN_ALL_INSETS_TOGGLE:
1027         case LFUN_STATISTICS:
1028         case LFUN_BRANCH_ADD_INSERT:
1029         case LFUN_KEYMAP_OFF:
1030         case LFUN_KEYMAP_PRIMARY:
1031         case LFUN_KEYMAP_SECONDARY:
1032         case LFUN_KEYMAP_TOGGLE:
1033                 flag.setEnabled(true);
1034                 break;
1035
1036         case LFUN_LABEL_COPY_AS_REF: {
1037                 // if there is an inset at cursor, see whether it
1038                 // handles the lfun
1039                 Inset * inset = cur.nextInset();
1040                 if (!inset || !inset->getStatus(cur, cmd, flag))
1041                         flag.setEnabled(false);
1042                 break;
1043         }
1044
1045         case LFUN_LABEL_GOTO: {
1046                 flag.setEnabled(!cmd.argument().empty()
1047                     || getInsetByCode<InsetRef>(cur, REF_CODE));
1048                 break;
1049         }
1050
1051         case LFUN_CHANGES_TRACK:
1052                 flag.setEnabled(true);
1053                 flag.setOnOff(buffer_.params().trackChanges);
1054                 break;
1055
1056         case LFUN_CHANGES_OUTPUT:
1057                 flag.setEnabled(true);
1058                 flag.setOnOff(buffer_.params().outputChanges);
1059                 break;
1060
1061         case LFUN_CHANGES_MERGE:
1062         case LFUN_CHANGE_NEXT:
1063         case LFUN_CHANGE_PREVIOUS:
1064         case LFUN_ALL_CHANGES_ACCEPT:
1065         case LFUN_ALL_CHANGES_REJECT:
1066                 // TODO: context-sensitive enabling of LFUNs
1067                 // In principle, these command should only be enabled if there
1068                 // is a change in the document. However, without proper
1069                 // optimizations, this will inevitably result in poor performance.
1070                 flag.setEnabled(true);
1071                 break;
1072
1073         case LFUN_BUFFER_TOGGLE_COMPRESSION: {
1074                 flag.setOnOff(buffer_.params().compressed);
1075                 break;
1076         }
1077         
1078         case LFUN_SCREEN_UP:
1079         case LFUN_SCREEN_DOWN:
1080         case LFUN_SCROLL:
1081         case LFUN_SCREEN_UP_SELECT:
1082         case LFUN_SCREEN_DOWN_SELECT:
1083         case LFUN_INSET_FORALL:
1084                 flag.setEnabled(true);
1085                 break;
1086
1087         case LFUN_LAYOUT_TABULAR:
1088                 flag.setEnabled(cur.innerInsetOfType(TABULAR_CODE));
1089                 break;
1090
1091         case LFUN_LAYOUT:
1092                 flag.setEnabled(!cur.inset().forcePlainLayout(cur.idx()));
1093                 break;
1094
1095         case LFUN_LAYOUT_PARAGRAPH:
1096                 flag.setEnabled(cur.inset().allowParagraphCustomization(cur.idx()));
1097                 break;
1098
1099         case LFUN_DIALOG_SHOW_NEW_INSET:
1100                 // FIXME: this is wrong, but I do not understand the
1101                 // intent (JMarc)
1102                 if (cur.inset().lyxCode() == CAPTION_CODE)
1103                         return cur.inset().getStatus(cur, cmd, flag);
1104                 // FIXME we should consider passthru paragraphs too.
1105                 flag.setEnabled(!cur.inset().getLayout().isPassThru());
1106                 break;
1107
1108         case LFUN_CITATION_INSERT: {
1109                 FuncRequest fr(LFUN_INSET_INSERT, "citation");
1110                 // FIXME: This could turn in a recursive hell.
1111                 // Shouldn't we use Buffer::getStatus() instead?
1112                 flag.setEnabled(lyx::getStatus(fr).enabled());
1113                 break;
1114         }
1115         case LFUN_INSET_APPLY: {
1116                 string const name = cmd.getArg(0);
1117                 Inset * inset = editedInset(name);
1118                 if (inset) {
1119                         FuncRequest fr(LFUN_INSET_MODIFY, cmd.argument());
1120                         FuncStatus fs;
1121                         if (!inset->getStatus(cur, fr, fs)) {
1122                                 // Every inset is supposed to handle this
1123                                 LASSERT(false, break);
1124                         }
1125                         flag |= fs;
1126                 } else {
1127                         FuncRequest fr(LFUN_INSET_INSERT, cmd.argument());
1128                         flag |= lyx::getStatus(fr);
1129                 }
1130                 break;
1131         }
1132
1133         default:
1134                 flag.setEnabled(false);
1135                 return false;
1136         }
1137
1138         return true;
1139 }
1140
1141
1142 Inset * BufferView::editedInset(string const & name) const
1143 {
1144         map<string, Inset *>::const_iterator it = d->edited_insets_.find(name);
1145         return it == d->edited_insets_.end() ? 0 : it->second;
1146 }
1147
1148
1149 void BufferView::editInset(string const & name, Inset * inset)
1150 {
1151         d->edited_insets_[name] = inset;
1152 }
1153
1154
1155 void BufferView::dispatch(FuncRequest const & cmd, DispatchResult & dr)
1156 {
1157         //lyxerr << [ cmd = " << cmd << "]" << endl;
1158
1159         // Make sure that the cached BufferView is correct.
1160         LYXERR(Debug::ACTION, " action[" << cmd.action << ']'
1161                 << " arg[" << to_utf8(cmd.argument()) << ']'
1162                 << " x[" << cmd.x << ']'
1163                 << " y[" << cmd.y << ']'
1164                 << " button[" << cmd.button() << ']');
1165
1166         string const argument = to_utf8(cmd.argument());
1167         Cursor & cur = d->cursor_;
1168
1169         // Don't dispatch function that does not apply to internal buffers.
1170         if (buffer_.isInternal() 
1171             && lyxaction.funcHasFlag(cmd.action, LyXAction::NoInternal))
1172                 return;
1173
1174         // We'll set this back to false if need be.
1175         bool dispatched = true;
1176         buffer_.undo().beginUndoGroup();
1177
1178         switch (cmd.action) {
1179
1180         case LFUN_BUFFER_PARAMS_APPLY: {
1181                 DocumentClass const * const oldClass = buffer_.params().documentClassPtr();
1182                 cur.recordUndoFullDocument();
1183                 istringstream ss(to_utf8(cmd.argument()));
1184                 Lexer lex;
1185                 lex.setStream(ss);
1186                 int const unknown_tokens = buffer_.readHeader(lex);
1187                 if (unknown_tokens != 0) {
1188                         LYXERR0("Warning in LFUN_BUFFER_PARAMS_APPLY!\n"
1189                                                 << unknown_tokens << " unknown token"
1190                                                 << (unknown_tokens == 1 ? "" : "s"));
1191                 }
1192                 updateDocumentClass(oldClass);
1193                         
1194                 // We are most certainly here because of a change in the document
1195                 // It is then better to make sure that all dialogs are in sync with
1196                 // current document settings.
1197                 dr.update(Update::Force | Update::FitCursor);
1198                 break;
1199         }
1200                 
1201         case LFUN_LAYOUT_MODULES_CLEAR: {
1202                 DocumentClass const * const oldClass =
1203                         buffer_.params().documentClassPtr();
1204                 cur.recordUndoFullDocument();
1205                 buffer_.params().clearLayoutModules();
1206                 buffer_.params().makeDocumentClass();
1207                 updateDocumentClass(oldClass);
1208                 dr.update(Update::Force | Update::FitCursor);
1209                 break;
1210         }
1211
1212         case LFUN_LAYOUT_MODULE_ADD: {
1213                 BufferParams const & params = buffer_.params();
1214                 if (!params.moduleCanBeAdded(argument)) {
1215                         LYXERR0("Module `" << argument << 
1216                                 "' cannot be added due to failed requirements or "
1217                                 "conflicts with installed modules.");
1218                         break;
1219                 }
1220                 DocumentClass const * const oldClass = params.documentClassPtr();
1221                 cur.recordUndoFullDocument();
1222                 buffer_.params().addLayoutModule(argument);
1223                 buffer_.params().makeDocumentClass();
1224                 updateDocumentClass(oldClass);
1225                 dr.update(Update::Force | Update::FitCursor);
1226                 break;
1227         }
1228
1229         case LFUN_TEXTCLASS_APPLY: {
1230                 if (!LayoutFileList::get().load(argument, buffer_.temppath()) &&
1231                         !LayoutFileList::get().load(argument, buffer_.filePath()))
1232                         break;
1233
1234                 LayoutFile const * old_layout = buffer_.params().baseClass();
1235                 LayoutFile const * new_layout = &(LayoutFileList::get()[argument]);
1236
1237                 if (old_layout == new_layout)
1238                         // nothing to do
1239                         break;
1240
1241                 //Save the old, possibly modular, layout for use in conversion.
1242                 DocumentClass const * const oldDocClass =
1243                         buffer_.params().documentClassPtr();
1244                 cur.recordUndoFullDocument();
1245                 buffer_.params().setBaseClass(argument);
1246                 buffer_.params().makeDocumentClass();
1247                 updateDocumentClass(oldDocClass);
1248                 dr.update(Update::Force | Update::FitCursor);
1249                 break;
1250         }
1251
1252         case LFUN_TEXTCLASS_LOAD:
1253                 LayoutFileList::get().load(argument, buffer_.temppath()) ||
1254                 LayoutFileList::get().load(argument, buffer_.filePath());
1255                 break;
1256
1257         case LFUN_LAYOUT_RELOAD: {
1258                 DocumentClass const * const oldClass = buffer_.params().documentClassPtr();
1259                 LayoutFileIndex bc = buffer_.params().baseClassID();
1260                 LayoutFileList::get().reset(bc);
1261                 buffer_.params().setBaseClass(bc);
1262                 buffer_.params().makeDocumentClass();
1263                 updateDocumentClass(oldClass);
1264                 dr.update(Update::Force | Update::FitCursor);
1265                 break;
1266         }
1267
1268         case LFUN_UNDO:
1269                 dr.setMessage(_("Undo"));
1270                 cur.clearSelection();
1271                 if (!cur.textUndo())
1272                         dr.setMessage(_("No further undo information"));
1273                 else
1274                         dr.update(Update::Force | Update::FitCursor);
1275                 break;
1276
1277         case LFUN_REDO:
1278                 dr.setMessage(_("Redo"));
1279                 cur.clearSelection();
1280                 if (!cur.textRedo())
1281                         dr.setMessage(_("No further redo information"));
1282                 else
1283                         dr.update(Update::Force | Update::FitCursor);
1284                 break;
1285
1286         case LFUN_FONT_STATE:
1287                 dr.setMessage(cur.currentState());
1288                 break;
1289
1290         case LFUN_BOOKMARK_SAVE:
1291                 saveBookmark(convert<unsigned int>(to_utf8(cmd.argument())));
1292                 break;
1293
1294         case LFUN_LABEL_GOTO: {
1295                 docstring label = cmd.argument();
1296                 if (label.empty()) {
1297                         InsetRef * inset =
1298                                 getInsetByCode<InsetRef>(cur, REF_CODE);
1299                         if (inset) {
1300                                 label = inset->getParam("reference");
1301                                 // persistent=false: use temp_bookmark
1302                                 saveBookmark(0);
1303                         }
1304                 }
1305                 if (!label.empty())
1306                         gotoLabel(label);
1307                 break;
1308         }
1309         
1310         case LFUN_INSET_EDIT: {
1311                 FuncRequest fr(cmd);
1312                 // if there is an inset at cursor, see whether it
1313                 // can be modified.
1314                 Inset * inset = cur.nextInset();
1315                 if (inset)
1316                         inset->dispatch(cur, fr);
1317                 // if it did not work, try the underlying inset.
1318                 if (!inset || !cur.result().dispatched())
1319                         cur.dispatch(cmd);
1320
1321                 // FIXME I'm adding the last break to solve a crash,
1322                 // but that is obviously not right.
1323                 if (!cur.result().dispatched())
1324                         // It did not work too; no action needed.
1325                         break;
1326                 break;
1327         }
1328
1329         case LFUN_PARAGRAPH_GOTO: {
1330                 int const id = convert<int>(cmd.getArg(0));
1331                 int const pos = convert<int>(cmd.getArg(1));
1332                 int i = 0;
1333                 for (Buffer * b = &buffer_; i == 0 || b != &buffer_;
1334                         b = theBufferList().next(b)) {
1335
1336                         DocIterator dit = b->getParFromID(id);
1337                         if (dit.atEnd()) {
1338                                 LYXERR(Debug::INFO, "No matching paragraph found! [" << id << "].");
1339                                 ++i;
1340                                 continue;
1341                         }
1342                         LYXERR(Debug::INFO, "Paragraph " << dit.paragraph().id()
1343                                 << " found in buffer `"
1344                                 << b->absFileName() << "'.");
1345
1346                         if (b == &buffer_) {
1347                                 // Set the cursor
1348                                 dit.pos() = pos;
1349                                 setCursor(dit);
1350                                 dr.update(Update::Force | Update::FitCursor);
1351                         } else {
1352                                 // Switch to other buffer view and resend cmd
1353                                 lyx::dispatch(FuncRequest(
1354                                         LFUN_BUFFER_SWITCH, b->absFileName()));
1355                                 lyx::dispatch(cmd);
1356                         }
1357                         break;
1358                 }
1359                 break;
1360         }
1361
1362         case LFUN_NOTE_NEXT:
1363                 gotoInset(this, NOTE_CODE, false);
1364                 break;
1365
1366         case LFUN_REFERENCE_NEXT: {
1367                 vector<InsetCode> tmp;
1368                 tmp.push_back(LABEL_CODE);
1369                 tmp.push_back(REF_CODE);
1370                 gotoInset(this, tmp, true);
1371                 break;
1372         }
1373
1374         case LFUN_CHANGES_TRACK:
1375                 buffer_.params().trackChanges = !buffer_.params().trackChanges;
1376                 break;
1377
1378         case LFUN_CHANGES_OUTPUT:
1379                 buffer_.params().outputChanges = !buffer_.params().outputChanges;
1380                 if (buffer_.params().outputChanges) {
1381                         bool dvipost    = LaTeXFeatures::isAvailable("dvipost");
1382                         bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
1383                                           LaTeXFeatures::isAvailable("xcolor");
1384
1385                         if (!dvipost && !xcolorulem) {
1386                                 Alert::warning(_("Changes not shown in LaTeX output"),
1387                                                _("Changes will not be highlighted in LaTeX output, "
1388                                                  "because neither dvipost nor xcolor/ulem are installed.\n"
1389                                                  "Please install these packages or redefine "
1390                                                  "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
1391                         } else if (!xcolorulem) {
1392                                 Alert::warning(_("Changes not shown in LaTeX output"),
1393                                                _("Changes will not be highlighted in LaTeX output "
1394                                                  "when using pdflatex, because xcolor and ulem are not installed.\n"
1395                                                  "Please install both packages or redefine "
1396                                                  "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
1397                         }
1398                 }
1399                 break;
1400
1401         case LFUN_CHANGE_NEXT:
1402                 findNextChange(this);
1403                 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1404                 dr.update(Update::Force | Update::FitCursor);
1405                 break;
1406         
1407         case LFUN_CHANGE_PREVIOUS:
1408                 findPreviousChange(this);
1409                 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1410                 dr.update(Update::Force | Update::FitCursor);
1411                 break;
1412
1413         case LFUN_CHANGES_MERGE:
1414                 if (findNextChange(this) || findPreviousChange(this)) {
1415                         dr.update(Update::Force | Update::FitCursor);
1416                         showDialog("changes");
1417                 }
1418                 break;
1419
1420         case LFUN_ALL_CHANGES_ACCEPT:
1421                 // select complete document
1422                 cur.reset();
1423                 cur.selHandle(true);
1424                 buffer_.text().cursorBottom(cur);
1425                 // accept everything in a single step to support atomic undo
1426                 buffer_.text().acceptOrRejectChanges(cur, Text::ACCEPT);
1427                 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1428                 dr.update(Update::Force | Update::FitCursor);
1429                 break;
1430
1431         case LFUN_ALL_CHANGES_REJECT:
1432                 // select complete document
1433                 cur.reset();
1434                 cur.selHandle(true);
1435                 buffer_.text().cursorBottom(cur);
1436                 // reject everything in a single step to support atomic undo
1437                 // Note: reject does not work recursively; the user may have to repeat the operation
1438                 buffer_.text().acceptOrRejectChanges(cur, Text::REJECT);
1439                 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1440                 dr.update(Update::Force | Update::FitCursor);
1441                 break;
1442
1443         case LFUN_WORD_FIND_FORWARD:
1444         case LFUN_WORD_FIND_BACKWARD: {
1445                 static docstring last_search;
1446                 docstring searched_string;
1447
1448                 if (!cmd.argument().empty()) {
1449                         last_search = cmd.argument();
1450                         searched_string = cmd.argument();
1451                 } else {
1452                         searched_string = last_search;
1453                 }
1454
1455                 if (searched_string.empty())
1456                         break;
1457
1458                 bool const fw = cmd.action == LFUN_WORD_FIND_FORWARD;
1459                 docstring const data =
1460                         find2string(searched_string, true, false, fw);
1461                 find(this, FuncRequest(LFUN_WORD_FIND, data));
1462                 break;
1463         }
1464
1465         case LFUN_WORD_FIND: {
1466                 FuncRequest req = cmd;
1467                 if (cmd.argument().empty() && !d->search_request_cache_.argument().empty())
1468                         req = d->search_request_cache_;
1469                 if (req.argument().empty()) {
1470                         lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, "findreplace"));
1471                         break;
1472                 }
1473                 if (find(this, req))
1474                         showCursor();
1475                 else
1476                         message(_("String not found!"));
1477                 d->search_request_cache_ = req;
1478                 break;
1479         }
1480
1481         case LFUN_WORD_REPLACE: {
1482                 bool has_deleted = false;
1483                 if (cur.selection()) {
1484                         DocIterator beg = cur.selectionBegin();
1485                         DocIterator end = cur.selectionEnd();
1486                         if (beg.pit() == end.pit()) {
1487                                 for (pos_type p = beg.pos() ; p < end.pos() ; ++p) {
1488                                         if (!cur.inMathed()
1489                                             && cur.paragraph().isDeleted(p))
1490                                                 has_deleted = true;
1491                                 }
1492                         }
1493                 }
1494                 replace(this, cmd, has_deleted);
1495                 break;
1496         }
1497
1498         case LFUN_WORD_FINDADV: {
1499                 FindAndReplaceOptions opt;
1500                 istringstream iss(to_utf8(cmd.argument()));
1501                 iss >> opt;
1502                 if (findAdv(this, opt))
1503                         cur.dispatched();
1504                 else
1505                         cur.undispatched();
1506                 break;
1507         }
1508
1509         case LFUN_MARK_OFF:
1510                 cur.clearSelection();
1511                 dr.setMessage(from_utf8(N_("Mark off")));
1512                 break;
1513
1514         case LFUN_MARK_ON:
1515                 cur.clearSelection();
1516                 cur.setMark(true);
1517                 dr.setMessage(from_utf8(N_("Mark on")));
1518                 break;
1519
1520         case LFUN_MARK_TOGGLE:
1521                 cur.setSelection(false);
1522                 if (cur.mark()) {
1523                         cur.setMark(false);
1524                         dr.setMessage(from_utf8(N_("Mark removed")));
1525                 } else {
1526                         cur.setMark(true);
1527                         dr.setMessage(from_utf8(N_("Mark set")));
1528                 }
1529                 cur.resetAnchor();
1530                 break;
1531
1532         case LFUN_SCREEN_SHOW_CURSOR:
1533                 showCursor();
1534                 break;
1535         
1536         case LFUN_SCREEN_RECENTER:
1537                 recenter();
1538                 break;
1539
1540         case LFUN_BIBTEX_DATABASE_ADD: {
1541                 Cursor tmpcur = cur;
1542                 findInset(tmpcur, BIBTEX_CODE, false);
1543                 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1544                                                 BIBTEX_CODE);
1545                 if (inset) {
1546                         if (inset->addDatabase(cmd.argument()))
1547                                 buffer_.updateBibfilesCache();
1548                 }
1549                 break;
1550         }
1551
1552         case LFUN_BIBTEX_DATABASE_DEL: {
1553                 Cursor tmpcur = cur;
1554                 findInset(tmpcur, BIBTEX_CODE, false);
1555                 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1556                                                 BIBTEX_CODE);
1557                 if (inset) {
1558                         if (inset->delDatabase(cmd.argument()))
1559                                 buffer_.updateBibfilesCache();
1560                 }
1561                 break;
1562         }
1563
1564         case LFUN_STATISTICS: {
1565                 DocIterator from, to;
1566                 if (cur.selection()) {
1567                         from = cur.selectionBegin();
1568                         to = cur.selectionEnd();
1569                 } else {
1570                         from = doc_iterator_begin(&buffer_);
1571                         to = doc_iterator_end(&buffer_);
1572                 }
1573                 int const words = countWords(from, to);
1574                 int const chars = countChars(from, to, false);
1575                 int const chars_blanks = countChars(from, to, true);
1576                 docstring message;
1577                 if (cur.selection())
1578                         message = _("Statistics for the selection:");
1579                 else
1580                         message = _("Statistics for the document:");
1581                 message += "\n\n";
1582                 if (words != 1)
1583                         message += bformat(_("%1$d words"), words);
1584                 else
1585                         message += _("One word");
1586                 message += "\n";
1587                 if (chars_blanks != 1)
1588                         message += bformat(_("%1$d characters (including blanks)"),
1589                                           chars_blanks);
1590                 else
1591                         message += _("One character (including blanks)");
1592                 message += "\n";
1593                 if (chars != 1)
1594                         message += bformat(_("%1$d characters (excluding blanks)"),
1595                                           chars);
1596                 else
1597                         message += _("One character (excluding blanks)");
1598
1599                 Alert::information(_("Statistics"), message);
1600         }
1601                 break;
1602
1603         case LFUN_BUFFER_TOGGLE_COMPRESSION:
1604                 // turn compression on/off
1605                 buffer_.params().compressed = !buffer_.params().compressed;
1606                 break;
1607
1608         case LFUN_LABEL_COPY_AS_REF: {
1609                 // if there is an inset at cursor, try to copy it
1610                 Inset * inset = &cur.inset();
1611                 if (!inset || !inset->asInsetMath())
1612                         inset = cur.nextInset();
1613                 if (inset) {
1614                         FuncRequest tmpcmd = cmd;
1615                         inset->dispatch(cur, tmpcmd);
1616                 }
1617                 if (!cur.result().dispatched())
1618                         // It did not work too; no action needed.
1619                         break;
1620                 cur.clearSelection();
1621                 dr.update(Update::SinglePar | Update::FitCursor);
1622                 break;
1623         }
1624
1625         case LFUN_SCREEN_UP:
1626         case LFUN_SCREEN_DOWN: {
1627                 Point p = getPos(cur, cur.boundary());
1628                 // This code has been commented out to enable to scroll down a
1629                 // document, even if there are large insets in it (see bug #5465).
1630                 /*if (p.y_ < 0 || p.y_ > height_) {
1631                         // The cursor is off-screen so recenter before proceeding.
1632                         showCursor();
1633                         p = getPos(cur, cur.boundary());
1634                 }*/
1635                 int const scrolled = scroll(cmd.action == LFUN_SCREEN_UP
1636                         ? -height_ : height_);
1637                 if (cmd.action == LFUN_SCREEN_UP && scrolled > -height_)
1638                         p = Point(0, 0);
1639                 if (cmd.action == LFUN_SCREEN_DOWN && scrolled < height_)
1640                         p = Point(width_, height_);
1641                 Cursor old = cur;
1642                 bool const in_texted = cur.inTexted();
1643                 cur.reset();
1644                 buffer_.changed(true);
1645                 updateHoveredInset();
1646
1647                 d->text_metrics_[&buffer_.text()].editXY(cur, p.x_, p.y_,
1648                         true, cmd.action == LFUN_SCREEN_UP); 
1649                 //FIXME: what to do with cur.x_target()?
1650                 bool update = in_texted && cur.bv().checkDepm(cur, old);
1651                 cur.finishUndo();
1652                 if (update)
1653                         dr.update(Update::Force | Update::FitCursor);
1654                 break;
1655         }
1656
1657         case LFUN_SCROLL:
1658                 lfunScroll(cmd);
1659                 break;
1660
1661         case LFUN_SCREEN_UP_SELECT: {
1662                 cur.selHandle(true);
1663                 if (isTopScreen()) {
1664                         lyx::dispatch(FuncRequest(LFUN_BUFFER_BEGIN_SELECT));
1665                         cur.finishUndo();
1666                         break;
1667                 }
1668                 int y = getPos(cur, cur.boundary()).y_;
1669                 int const ymin = y - height_ + defaultRowHeight();
1670                 while (y > ymin && cur.up())
1671                         y = getPos(cur, cur.boundary()).y_;
1672
1673                 cur.finishUndo();
1674                 dr.update(Update::SinglePar | Update::FitCursor);
1675                 break;
1676         }
1677
1678         case LFUN_SCREEN_DOWN_SELECT: {
1679                 cur.selHandle(true);
1680                 if (isBottomScreen()) {
1681                         lyx::dispatch(FuncRequest(LFUN_BUFFER_END_SELECT));
1682                         cur.finishUndo();
1683                         break;
1684                 }
1685                 int y = getPos(cur, cur.boundary()).y_;
1686                 int const ymax = y + height_ - defaultRowHeight();
1687                 while (y < ymax && cur.down())
1688                         y = getPos(cur, cur.boundary()).y_;
1689
1690                 cur.finishUndo();
1691                 dr.update(Update::SinglePar | Update::FitCursor);
1692                 break;
1693         }
1694
1695
1696         // This would be in Buffer class if only Cursor did not
1697         // require a bufferview
1698         case LFUN_INSET_FORALL: {
1699                 docstring const name = from_utf8(cmd.getArg(0));
1700                 string const commandstr = cmd.getLongArg(1);
1701                 FuncRequest const fr = lyxaction.lookupFunc(commandstr);
1702
1703                 // an arbitrary number to limit number of iterations
1704                 const int max_iter = 10000;
1705                 int iterations = 0;
1706                 Cursor & cur = d->cursor_;
1707                 Cursor const savecur = cur;
1708                 cur.reset();
1709                 if (!cur.nextInset())
1710                         cur.forwardInset();
1711                 cur.beginUndoGroup();
1712                 while(cur && iterations < max_iter) {
1713                         Inset * ins = cur.nextInset();
1714                         if (!ins)
1715                                 break;
1716                         docstring insname = ins->name();
1717                         while (!insname.empty()) {
1718                                 if (insname == name || name == from_utf8("*")) {
1719                                         cur.recordUndo();
1720                                         lyx::dispatch(fr);
1721                                         ++iterations;
1722                                         break;
1723                                 }
1724                                 size_t const i = insname.rfind(':');
1725                                 if (i == string::npos)
1726                                         break;
1727                                 insname = insname.substr(0, i);
1728                         }
1729                         cur.forwardInset();
1730                 }
1731                 cur.endUndoGroup();
1732                 cur = savecur;
1733                 cur.fixIfBroken();
1734                 dr.update(Update::Force);
1735
1736                 if (iterations >= max_iter) {
1737                         dr.setError(true);
1738                         dr.setMessage(bformat(_("`inset-forall' interrupted because number of actions is larger than %1$d"), max_iter));
1739                 } else
1740                         dr.setMessage(bformat(_("Applied \"%1$s\" to %2$d insets"), from_utf8(commandstr), iterations));
1741                 break;
1742         }
1743
1744
1745         case LFUN_ALL_INSETS_TOGGLE: {
1746                 string action;
1747                 string const name = split(to_utf8(cmd.argument()), action, ' ');
1748                 InsetCode const inset_code = insetCode(name);
1749
1750                 FuncRequest fr(LFUN_INSET_TOGGLE, action);
1751
1752                 Inset & inset = cur.buffer()->inset();
1753                 InsetIterator it  = inset_iterator_begin(inset);
1754                 InsetIterator const end = inset_iterator_end(inset);
1755                 for (; it != end; ++it) {
1756                         if (it->asInsetCollapsable()
1757                             && (inset_code == NO_CODE
1758                             || inset_code == it->lyxCode())) {
1759                                 Cursor tmpcur = cur;
1760                                 tmpcur.pushBackward(*it);
1761                                 it->dispatch(tmpcur, fr);
1762                         }
1763                 }
1764                 dr.update(Update::Force | Update::FitCursor);
1765                 break;
1766         }
1767
1768         case LFUN_BRANCH_ADD_INSERT: {
1769                 docstring branch_name = from_utf8(cmd.getArg(0));
1770                 if (branch_name.empty())
1771                         if (!Alert::askForText(branch_name, _("Branch name")) ||
1772                                                 branch_name.empty())
1773                                 break;
1774
1775                 DispatchResult drtmp;
1776                 buffer_.dispatch(FuncRequest(LFUN_BRANCH_ADD, branch_name), drtmp);
1777                 if (drtmp.error()) {
1778                         Alert::warning(_("Branch already exists"), drtmp.message());
1779                         break;
1780                 }
1781                 lyx::dispatch(FuncRequest(LFUN_BRANCH_INSERT, branch_name));
1782                 break;
1783         }
1784
1785         case LFUN_KEYMAP_OFF:
1786                 getIntl().keyMapOn(false);
1787                 break;
1788
1789         case LFUN_KEYMAP_PRIMARY:
1790                 getIntl().keyMapPrim();
1791                 break;
1792
1793         case LFUN_KEYMAP_SECONDARY:
1794                 getIntl().keyMapSec();
1795                 break;
1796
1797         case LFUN_KEYMAP_TOGGLE:
1798                 getIntl().toggleKeyMap();
1799                 break;
1800
1801         case LFUN_DIALOG_SHOW_NEW_INSET: {
1802                 string const name = cmd.getArg(0);
1803                 string data = trim(to_utf8(cmd.argument()).substr(name.size()));
1804                 if (decodeInsetParam(name, data, buffer_))
1805                         lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, name + " " + data));
1806                 else
1807                         lyxerr << "Inset type '" << name << 
1808                         "' not recognized in LFUN_DIALOG_SHOW_NEW_INSET" <<  endl;
1809                 break;
1810         }
1811
1812         case LFUN_CITATION_INSERT: {
1813                 if (argument.empty()) {
1814                         lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW_NEW_INSET, "citation"));
1815                         break;
1816                 }
1817                 // we can have one optional argument, delimited by '|'
1818                 // citation-insert <key>|<text_before>
1819                 // this should be enhanced to also support text_after
1820                 // and citation style
1821                 string arg = argument;
1822                 string opt1;
1823                 if (contains(argument, "|")) {
1824                         arg = token(argument, '|', 0);
1825                         opt1 = token(argument, '|', 1);
1826                 }
1827                 InsetCommandParams icp(CITE_CODE);
1828                 icp["key"] = from_utf8(arg);
1829                 if (!opt1.empty())
1830                         icp["before"] = from_utf8(opt1);
1831                 string icstr = InsetCommand::params2string("citation", icp);
1832                 FuncRequest fr(LFUN_INSET_INSERT, icstr);
1833                 lyx::dispatch(fr);
1834                 break;
1835         }
1836
1837         case LFUN_INSET_APPLY: {
1838                 string const name = cmd.getArg(0);
1839                 Inset * inset = editedInset(name);
1840                 if (!inset) {
1841                         FuncRequest fr(LFUN_INSET_INSERT, cmd.argument());
1842                         lyx::dispatch(fr);
1843                         break;
1844                 }
1845                 // put cursor in front of inset.
1846                 if (!setCursorFromInset(inset)) {
1847                         LASSERT(false, break);
1848                 }
1849                 cur.recordUndo();
1850                 FuncRequest fr(LFUN_INSET_MODIFY, cmd.argument());
1851                 inset->dispatch(cur, fr);
1852                 dr.update(Update::SinglePar | Update::FitCursor);
1853                 break;
1854         }
1855
1856         default:
1857                 dispatched = false;
1858                 break;
1859         }
1860
1861         buffer_.undo().endUndoGroup();
1862         dr.dispatched(dispatched);
1863         return;
1864 }
1865
1866
1867 docstring const BufferView::requestSelection()
1868 {
1869         Cursor & cur = d->cursor_;
1870
1871         LYXERR(Debug::SELECTION, "requestSelection: cur.selection: " << cur.selection());
1872         if (!cur.selection()) {
1873                 d->xsel_cache_.set = false;
1874                 return docstring();
1875         }
1876
1877         LYXERR(Debug::SELECTION, "requestSelection: xsel_cache.set: " << d->xsel_cache_.set);
1878         if (!d->xsel_cache_.set ||
1879             cur.top() != d->xsel_cache_.cursor ||
1880             cur.anchor_.top() != d->xsel_cache_.anchor)
1881         {
1882                 d->xsel_cache_.cursor = cur.top();
1883                 d->xsel_cache_.anchor = cur.anchor_.top();
1884                 d->xsel_cache_.set = cur.selection();
1885                 return cur.selectionAsString(false);
1886         }
1887         return docstring();
1888 }
1889
1890
1891 void BufferView::clearSelection()
1892 {
1893         d->cursor_.clearSelection();
1894         // Clear the selection buffer. Otherwise a subsequent
1895         // middle-mouse-button paste would use the selection buffer,
1896         // not the more current external selection.
1897         cap::clearSelection();
1898         d->xsel_cache_.set = false;
1899         // The buffer did not really change, but this causes the
1900         // redraw we need because we cleared the selection above.
1901         buffer_.changed(false);
1902 }
1903
1904
1905 void BufferView::resize(int width, int height)
1906 {
1907         // Update from work area
1908         width_ = width;
1909         height_ = height;
1910
1911         // Clear the paragraph height cache.
1912         d->par_height_.clear();
1913         // Redo the metrics.
1914         updateMetrics();
1915 }
1916
1917
1918 Inset const * BufferView::getCoveringInset(Text const & text,
1919                 int x, int y) const
1920 {
1921         TextMetrics & tm = d->text_metrics_[&text];
1922         Inset * inset = tm.checkInsetHit(x, y);
1923         if (!inset)
1924                 return 0;
1925
1926         if (!inset->descendable(*this))
1927                 // No need to go further down if the inset is not
1928                 // descendable.
1929                 return inset;
1930
1931         size_t cell_number = inset->nargs();
1932         // Check all the inner cell.
1933         for (size_t i = 0; i != cell_number; ++i) {
1934                 Text const * inner_text = inset->getText(i);
1935                 if (inner_text) {
1936                         // Try deeper.
1937                         Inset const * inset_deeper =
1938                                 getCoveringInset(*inner_text, x, y);
1939                         if (inset_deeper)
1940                                 return inset_deeper;
1941                 }
1942         }
1943
1944         return inset;
1945 }
1946
1947
1948 void BufferView::updateHoveredInset() const
1949 {
1950         // Get inset under mouse, if there is one.
1951         Inset const * covering_inset = getCoveringInset(buffer_.text(),
1952                         d->mouse_position_cache_.x_, d->mouse_position_cache_.y_);
1953         if (covering_inset == d->last_inset_)
1954                 // Same inset, no need to do anything...
1955                 return;
1956
1957         bool need_redraw = false;
1958         if (d->last_inset_)
1959                 // Remove the hint on the last hovered inset (if any).
1960                 need_redraw |= d->last_inset_->setMouseHover(false);
1961         
1962         // const_cast because of setMouseHover().
1963         Inset * inset = const_cast<Inset *>(covering_inset);
1964         if (inset)
1965                 // Highlight the newly hovered inset (if any).
1966                 need_redraw |= inset->setMouseHover(true);
1967
1968         d->last_inset_ = inset;
1969         
1970         if (need_redraw) {
1971                 LYXERR(Debug::PAINTING, "Mouse hover detected at: ("
1972                                 << d->mouse_position_cache_.x_ << ", " 
1973                                 << d->mouse_position_cache_.y_ << ")");
1974         
1975                 d->update_strategy_ = DecorationUpdate;
1976
1977                 // This event (moving without mouse click) is not passed further.
1978                 // This should be changed if it is further utilized.
1979                 buffer_.changed(false);
1980         }
1981 }
1982
1983
1984 void BufferView::mouseEventDispatch(FuncRequest const & cmd0)
1985 {
1986         //lyxerr << "[ cmd0 " << cmd0 << "]" << endl;
1987
1988         // This is only called for mouse related events including
1989         // LFUN_FILE_OPEN generated by drag-and-drop.
1990         FuncRequest cmd = cmd0;
1991
1992         Cursor old = cursor();
1993         Cursor cur(*this);
1994         cur.push(buffer_.inset());
1995         cur.setSelection(d->cursor_.selection());
1996
1997         // Either the inset under the cursor or the
1998         // surrounding Text will handle this event.
1999
2000         // make sure we stay within the screen...
2001         cmd.y = min(max(cmd.y, -1), height_);
2002
2003         d->mouse_position_cache_.x_ = cmd.x;
2004         d->mouse_position_cache_.y_ = cmd.y;
2005
2006         if (cmd.action == LFUN_MOUSE_MOTION && cmd.button() == mouse_button::none) {
2007                 updateHoveredInset();
2008                 return;
2009         }
2010
2011         // Build temporary cursor.
2012         Inset * inset = d->text_metrics_[&buffer_.text()].editXY(cur, cmd.x, cmd.y);
2013
2014         // Put anchor at the same position.
2015         cur.resetAnchor();
2016
2017         cur.beginUndoGroup();
2018
2019         // Try to dispatch to an non-editable inset near this position
2020         // via the temp cursor. If the inset wishes to change the real
2021         // cursor it has to do so explicitly by using
2022         //  cur.bv().cursor() = cur;  (or similar)
2023         if (inset)
2024                 inset->dispatch(cur, cmd);
2025
2026         // Now dispatch to the temporary cursor. If the real cursor should
2027         // be modified, the inset's dispatch has to do so explicitly.
2028         if (!inset || !cur.result().dispatched())
2029                 cur.dispatch(cmd);
2030
2031         cur.endUndoGroup();
2032
2033         // Notify left insets
2034         if (cur != old) {
2035                 old.fixIfBroken();
2036                 bool badcursor = notifyCursorLeavesOrEnters(old, cur);
2037                 if (badcursor)
2038                         cursor().fixIfBroken();
2039         }
2040         
2041         // Do we have a selection?
2042         theSelection().haveSelection(cursor().selection());
2043
2044         // If the command has been dispatched,
2045         if (cur.result().dispatched() || cur.result().update())
2046                 processUpdateFlags(cur.result().update());
2047 }
2048
2049
2050 void BufferView::lfunScroll(FuncRequest const & cmd)
2051 {
2052         string const scroll_type = cmd.getArg(0);
2053         int const scroll_step = 
2054                 (scroll_type == "line") ? d->scrollbarParameters_.single_step
2055                 : (scroll_type == "page") ? d->scrollbarParameters_.page_step : 0;
2056         if (scroll_step == 0)
2057                 return;
2058         string const scroll_quantity = cmd.getArg(1);
2059         if (scroll_quantity == "up")
2060                 scrollUp(scroll_step);
2061         else if (scroll_quantity == "down")
2062                 scrollDown(scroll_step);
2063         else {
2064                 int const scroll_value = convert<int>(scroll_quantity);
2065                 if (scroll_value)
2066                         scroll(scroll_step * scroll_value);
2067         }
2068         buffer_.changed(true);
2069         updateHoveredInset();
2070 }
2071
2072
2073 int BufferView::minVisiblePart()
2074 {
2075         return 2 * defaultRowHeight();
2076 }
2077
2078
2079 int BufferView::scroll(int y)
2080 {
2081         if (y > 0)
2082                 return scrollDown(y);
2083         if (y < 0)
2084                 return scrollUp(-y);
2085         return 0;
2086 }
2087
2088
2089 int BufferView::scrollDown(int offset)
2090 {
2091         Text * text = &buffer_.text();
2092         TextMetrics & tm = d->text_metrics_[text];
2093         int const ymax = height_ + offset;
2094         while (true) {
2095                 pair<pit_type, ParagraphMetrics const *> last = tm.last();
2096                 int bottom_pos = last.second->position() + last.second->descent();
2097                 if (lyxrc.scroll_below_document)
2098                         bottom_pos += height_ - minVisiblePart();
2099                 if (last.first + 1 == int(text->paragraphs().size())) {
2100                         if (bottom_pos <= height_)
2101                                 return 0;
2102                         offset = min(offset, bottom_pos - height_);
2103                         break;
2104                 }
2105                 if (bottom_pos > ymax)
2106                         break;
2107                 tm.newParMetricsDown();
2108         }
2109         d->anchor_ypos_ -= offset;
2110         return -offset;
2111 }
2112
2113
2114 int BufferView::scrollUp(int offset)
2115 {
2116         Text * text = &buffer_.text();
2117         TextMetrics & tm = d->text_metrics_[text];
2118         int ymin = - offset;
2119         while (true) {
2120                 pair<pit_type, ParagraphMetrics const *> first = tm.first();
2121                 int top_pos = first.second->position() - first.second->ascent();
2122                 if (first.first == 0) {
2123                         if (top_pos >= 0)
2124                                 return 0;
2125                         offset = min(offset, - top_pos);
2126                         break;
2127                 }
2128                 if (top_pos < ymin)
2129                         break;
2130                 tm.newParMetricsUp();
2131         }
2132         d->anchor_ypos_ += offset;
2133         return offset;
2134 }
2135
2136
2137 void BufferView::setCursorFromRow(int row)
2138 {
2139         int tmpid = -1;
2140         int tmppos = -1;
2141
2142         buffer_.texrow().getIdFromRow(row, tmpid, tmppos);
2143
2144         d->cursor_.reset();
2145         if (tmpid == -1)
2146                 buffer_.text().setCursor(d->cursor_, 0, 0);
2147         else
2148                 buffer_.text().setCursor(d->cursor_, buffer_.getParFromID(tmpid).pit(), tmppos);
2149         recenter();
2150 }
2151
2152
2153 bool BufferView::setCursorFromInset(Inset const * inset)
2154 {
2155         // are we already there?
2156         if (cursor().nextInset() == inset)
2157                 return true;
2158
2159         // Inset is not at cursor position. Find it in the document.
2160         Cursor cur(*this);
2161         cur.reset();
2162         while (cur && cur.nextInset() != inset)
2163                 cur.forwardInset();
2164
2165         if (cur) {
2166                 setCursor(cur);
2167                 return true;
2168         }
2169         return false;
2170 }
2171
2172
2173 void BufferView::gotoLabel(docstring const & label)
2174 {
2175         std::vector<Buffer const *> bufs = buffer().allRelatives();
2176         std::vector<Buffer const *>::iterator it = bufs.begin();
2177         for (; it != bufs.end(); ++it) {
2178                 Buffer const * buf = *it;
2179
2180                 // find label
2181                 Toc & toc = buf->tocBackend().toc("label");
2182                 TocIterator toc_it = toc.begin();
2183                 TocIterator end = toc.end();
2184                 for (; toc_it != end; ++toc_it) {
2185                         if (label == toc_it->str()) {
2186                                 lyx::dispatch(toc_it->action());
2187                                 return;
2188                         }
2189                 }
2190         }
2191 }
2192
2193
2194 TextMetrics const & BufferView::textMetrics(Text const * t) const
2195 {
2196         return const_cast<BufferView *>(this)->textMetrics(t);
2197 }
2198
2199
2200 TextMetrics & BufferView::textMetrics(Text const * t)
2201 {
2202         TextMetricsCache::iterator tmc_it  = d->text_metrics_.find(t);
2203         if (tmc_it == d->text_metrics_.end()) {
2204                 tmc_it = d->text_metrics_.insert(
2205                         make_pair(t, TextMetrics(this, const_cast<Text *>(t)))).first;
2206         }
2207         return tmc_it->second;
2208 }
2209
2210
2211 ParagraphMetrics const & BufferView::parMetrics(Text const * t,
2212                 pit_type pit) const
2213 {
2214         return textMetrics(t).parMetrics(pit);
2215 }
2216
2217
2218 int BufferView::workHeight() const
2219 {
2220         return height_;
2221 }
2222
2223
2224 void BufferView::setCursor(DocIterator const & dit)
2225 {
2226         d->cursor_.reset();
2227         size_t const n = dit.depth();
2228         for (size_t i = 0; i < n; ++i)
2229                 dit[i].inset().edit(d->cursor_, true);
2230
2231         d->cursor_.setCursor(dit);
2232         d->cursor_.setSelection(false);
2233 }
2234
2235
2236 bool BufferView::checkDepm(Cursor & cur, Cursor & old)
2237 {
2238         // Would be wrong to delete anything if we have a selection.
2239         if (cur.selection())
2240                 return false;
2241
2242         bool need_anchor_change = false;
2243         bool changed = d->cursor_.text()->deleteEmptyParagraphMechanism(cur, old,
2244                 need_anchor_change);
2245
2246         if (need_anchor_change)
2247                 cur.resetAnchor();
2248
2249         if (!changed)
2250                 return false;
2251
2252         d->cursor_ = cur;
2253
2254         buffer_.updateBuffer();
2255         buffer_.changed(true);
2256         return true;
2257 }
2258
2259
2260 bool BufferView::mouseSetCursor(Cursor & cur, bool select)
2261 {
2262         LASSERT(&cur.bv() == this, /**/);
2263
2264         if (!select)
2265                 // this event will clear selection so we save selection for
2266                 // persistent selection
2267                 cap::saveSelection(cursor());
2268
2269         d->cursor_.macroModeClose();
2270
2271         // Has the cursor just left the inset?
2272         bool leftinset = (&d->cursor_.inset() != &cur.inset());
2273         if (leftinset)
2274                 d->cursor_.fixIfBroken();
2275
2276         // FIXME: shift-mouse selection doesn't work well across insets.
2277         bool do_selection = select && &d->cursor_.anchor().inset() == &cur.inset();
2278
2279         // do the dEPM magic if needed
2280         // FIXME: (1) move this to InsetText::notifyCursorLeaves?
2281         // FIXME: (2) if we had a working InsetText::notifyCursorLeaves,
2282         // the leftinset bool would not be necessary (badcursor instead).
2283         bool update = leftinset;
2284         if (!do_selection && d->cursor_.inTexted())
2285                 update |= checkDepm(cur, d->cursor_);
2286
2287         if (!do_selection)
2288                 d->cursor_.resetAnchor();
2289         d->cursor_.setCursor(cur);
2290         d->cursor_.boundary(cur.boundary());
2291         if (do_selection)
2292                 d->cursor_.setSelection();
2293         else
2294                 d->cursor_.clearSelection();
2295
2296         d->cursor_.finishUndo();
2297         d->cursor_.setCurrentFont();
2298         return update;
2299 }
2300
2301
2302 void BufferView::putSelectionAt(DocIterator const & cur,
2303                                 int length, bool backwards)
2304 {
2305         d->cursor_.clearSelection();
2306
2307         setCursor(cur);
2308
2309         if (length) {
2310                 if (backwards) {
2311                         d->cursor_.pos() += length;
2312                         d->cursor_.setSelection(d->cursor_, -length);
2313                 } else
2314                         d->cursor_.setSelection(d->cursor_, length);
2315         }
2316         // Ensure a redraw happens in any case because the new selection could 
2317         // possibly be on the same screen as the previous selection.
2318         processUpdateFlags(Update::Force | Update::FitCursor);
2319 }
2320
2321
2322 Cursor & BufferView::cursor()
2323 {
2324         return d->cursor_;
2325 }
2326
2327
2328 Cursor const & BufferView::cursor() const
2329 {
2330         return d->cursor_;
2331 }
2332
2333
2334 pit_type BufferView::anchor_ref() const
2335 {
2336         return d->anchor_pit_;
2337 }
2338
2339
2340 bool BufferView::singleParUpdate()
2341 {
2342         Text & buftext = buffer_.text();
2343         pit_type const bottom_pit = d->cursor_.bottom().pit();
2344         TextMetrics & tm = textMetrics(&buftext);
2345         int old_height = tm.parMetrics(bottom_pit).height();
2346
2347         // make sure inline completion pointer is ok
2348         if (d->inlineCompletionPos_.fixIfBroken())
2349                 d->inlineCompletionPos_ = DocIterator();
2350
2351         // In Single Paragraph mode, rebreak only
2352         // the (main text, not inset!) paragraph containing the cursor.
2353         // (if this paragraph contains insets etc., rebreaking will
2354         // recursively descend)
2355         tm.redoParagraph(bottom_pit);
2356         ParagraphMetrics const & pm = tm.parMetrics(bottom_pit);                
2357         if (pm.height() != old_height)
2358                 // Paragraph height has changed so we cannot proceed to
2359                 // the singlePar optimisation.
2360                 return false;
2361
2362         d->update_strategy_ = SingleParUpdate;
2363
2364         LYXERR(Debug::PAINTING, "\ny1: " << pm.position() - pm.ascent()
2365                 << " y2: " << pm.position() + pm.descent()
2366                 << " pit: " << bottom_pit
2367                 << " singlepar: 1");
2368         return true;
2369 }
2370
2371
2372 void BufferView::updateMetrics()
2373 {
2374         if (height_ == 0 || width_ == 0)
2375                 return;
2376
2377         Text & buftext = buffer_.text();
2378         pit_type const npit = int(buftext.paragraphs().size());
2379
2380         // Clear out the position cache in case of full screen redraw,
2381         d->coord_cache_.clear();
2382
2383         // Clear out paragraph metrics to avoid having invalid metrics
2384         // in the cache from paragraphs not relayouted below
2385         // The complete text metrics will be redone.
2386         d->text_metrics_.clear();
2387
2388         TextMetrics & tm = textMetrics(&buftext);
2389
2390         // make sure inline completion pointer is ok
2391         if (d->inlineCompletionPos_.fixIfBroken())
2392                 d->inlineCompletionPos_ = DocIterator();
2393         
2394         if (d->anchor_pit_ >= npit)
2395                 // The anchor pit must have been deleted...
2396                 d->anchor_pit_ = npit - 1;
2397
2398         // Rebreak anchor paragraph.
2399         tm.redoParagraph(d->anchor_pit_);
2400         ParagraphMetrics & anchor_pm = tm.par_metrics_[d->anchor_pit_];
2401         
2402         // position anchor
2403         if (d->anchor_pit_ == 0) {
2404                 int scrollRange = d->scrollbarParameters_.max - d->scrollbarParameters_.min;
2405                 
2406                 // Complete buffer visible? Then it's easy.
2407                 if (scrollRange == 0)
2408                         d->anchor_ypos_ = anchor_pm.ascent();
2409         
2410                 // FIXME: Some clever handling needed to show
2411                 // the _first_ paragraph up to the top if the cursor is
2412                 // in the first line.
2413         }               
2414         anchor_pm.setPosition(d->anchor_ypos_);
2415
2416         LYXERR(Debug::PAINTING, "metrics: "
2417                 << " anchor pit = " << d->anchor_pit_
2418                 << " anchor ypos = " << d->anchor_ypos_);
2419
2420         // Redo paragraphs above anchor if necessary.
2421         int y1 = d->anchor_ypos_ - anchor_pm.ascent();
2422         // We are now just above the anchor paragraph.
2423         pit_type pit1 = d->anchor_pit_ - 1;
2424         for (; pit1 >= 0 && y1 >= 0; --pit1) {
2425                 tm.redoParagraph(pit1);
2426                 ParagraphMetrics & pm = tm.par_metrics_[pit1];
2427                 y1 -= pm.descent();
2428                 // Save the paragraph position in the cache.
2429                 pm.setPosition(y1);
2430                 y1 -= pm.ascent();
2431         }
2432
2433         // Redo paragraphs below the anchor if necessary.
2434         int y2 = d->anchor_ypos_ + anchor_pm.descent();
2435         // We are now just below the anchor paragraph.
2436         pit_type pit2 = d->anchor_pit_ + 1;
2437         for (; pit2 < npit && y2 <= height_; ++pit2) {
2438                 tm.redoParagraph(pit2);
2439                 ParagraphMetrics & pm = tm.par_metrics_[pit2];
2440                 y2 += pm.ascent();
2441                 // Save the paragraph position in the cache.
2442                 pm.setPosition(y2);
2443                 y2 += pm.descent();
2444         }
2445
2446         LYXERR(Debug::PAINTING, "Metrics: "
2447                 << " anchor pit = " << d->anchor_pit_
2448                 << " anchor ypos = " << d->anchor_ypos_
2449                 << " y1 = " << y1
2450                 << " y2 = " << y2
2451                 << " pit1 = " << pit1
2452                 << " pit2 = " << pit2);
2453
2454         d->update_strategy_ = FullScreenUpdate;
2455
2456         if (lyxerr.debugging(Debug::WORKAREA)) {
2457                 LYXERR(Debug::WORKAREA, "BufferView::updateMetrics");
2458                 d->coord_cache_.dump();
2459         }
2460 }
2461
2462
2463 void BufferView::insertLyXFile(FileName const & fname)
2464 {
2465         LASSERT(d->cursor_.inTexted(), /**/);
2466
2467         // Get absolute path of file and add ".lyx"
2468         // to the filename if necessary
2469         FileName filename = fileSearch(string(), fname.absFilename(), "lyx");
2470
2471         docstring const disp_fn = makeDisplayPath(filename.absFilename());
2472         // emit message signal.
2473         message(bformat(_("Inserting document %1$s..."), disp_fn));
2474
2475         docstring res;
2476         Buffer buf("", false);
2477         if (buf.loadLyXFile(filename)) {
2478                 ErrorList & el = buffer_.errorList("Parse");
2479                 // Copy the inserted document error list into the current buffer one.
2480                 el = buf.errorList("Parse");
2481                 buffer_.undo().recordUndo(d->cursor_);
2482                 cap::pasteParagraphList(d->cursor_, buf.paragraphs(),
2483                                              buf.params().documentClassPtr(), el);
2484                 res = _("Document %1$s inserted.");
2485         } else {
2486                 res = _("Could not insert document %1$s");
2487         }
2488
2489         buffer_.changed(true);
2490         // emit message signal.
2491         message(bformat(res, disp_fn));
2492         buffer_.errors("Parse");
2493 }
2494
2495
2496 Point BufferView::coordOffset(DocIterator const & dit, bool boundary) const
2497 {
2498         int x = 0;
2499         int y = 0;
2500         int lastw = 0;
2501
2502         // Addup contribution of nested insets, from inside to outside,
2503         // keeping the outer paragraph for a special handling below
2504         for (size_t i = dit.depth() - 1; i >= 1; --i) {
2505                 CursorSlice const & sl = dit[i];
2506                 int xx = 0;
2507                 int yy = 0;
2508                 
2509                 // get relative position inside sl.inset()
2510                 sl.inset().cursorPos(*this, sl, boundary && (i + 1 == dit.depth()), xx, yy);
2511                 
2512                 // Make relative position inside of the edited inset relative to sl.inset()
2513                 x += xx;
2514                 y += yy;
2515                 
2516                 // In case of an RTL inset, the edited inset will be positioned to the left
2517                 // of xx:yy
2518                 if (sl.text()) {
2519                         bool boundary_i = boundary && i + 1 == dit.depth();
2520                         bool rtl = textMetrics(sl.text()).isRTL(sl, boundary_i);
2521                         if (rtl)
2522                                 x -= lastw;
2523                 }
2524
2525                 // remember width for the case that sl.inset() is positioned in an RTL inset
2526                 if (i && dit[i - 1].text()) {
2527                         // If this Inset is inside a Text Inset, retrieve the Dimension
2528                         // from the containing text instead of using Inset::dimension() which
2529                         // might not be implemented.
2530                         // FIXME (Abdel 23/09/2007): this is a bit messy because of the
2531                         // elimination of Inset::dim_ cache. This coordOffset() method needs
2532                         // to be rewritten in light of the new design.
2533                         Dimension const & dim = parMetrics(dit[i - 1].text(),
2534                                 dit[i - 1].pit()).insetDimension(&sl.inset());
2535                         lastw = dim.wid;
2536                 } else {
2537                         Dimension const dim = sl.inset().dimension(*this);
2538                         lastw = dim.wid;
2539                 }
2540                 
2541                 //lyxerr << "Cursor::getPos, i: "
2542                 // << i << " x: " << xx << " y: " << y << endl;
2543         }
2544
2545         // Add contribution of initial rows of outermost paragraph
2546         CursorSlice const & sl = dit[0];
2547         TextMetrics const & tm = textMetrics(sl.text());
2548         ParagraphMetrics const & pm = tm.parMetrics(sl.pit());
2549         LASSERT(!pm.rows().empty(), /**/);
2550         y -= pm.rows()[0].ascent();
2551 #if 1
2552         // FIXME: document this mess
2553         size_t rend;
2554         if (sl.pos() > 0 && dit.depth() == 1) {
2555                 int pos = sl.pos();
2556                 if (pos && boundary)
2557                         --pos;
2558 //              lyxerr << "coordOffset: boundary:" << boundary << " depth:" << dit.depth() << " pos:" << pos << " sl.pos:" << sl.pos() << endl;
2559                 rend = pm.pos2row(pos);
2560         } else
2561                 rend = pm.pos2row(sl.pos());
2562 #else
2563         size_t rend = pm.pos2row(sl.pos());
2564 #endif
2565         for (size_t rit = 0; rit != rend; ++rit)
2566                 y += pm.rows()[rit].height();
2567         y += pm.rows()[rend].ascent();
2568         
2569         TextMetrics const & bottom_tm = textMetrics(dit.bottom().text());
2570         
2571         // Make relative position from the nested inset now bufferview absolute.
2572         int xx = bottom_tm.cursorX(dit.bottom(), boundary && dit.depth() == 1);
2573         x += xx;
2574         
2575         // In the RTL case place the nested inset at the left of the cursor in 
2576         // the outer paragraph
2577         bool boundary_1 = boundary && 1 == dit.depth();
2578         bool rtl = bottom_tm.isRTL(dit.bottom(), boundary_1);
2579         if (rtl)
2580                 x -= lastw;
2581         
2582         return Point(x, y);
2583 }
2584
2585
2586 Point BufferView::getPos(DocIterator const & dit, bool boundary) const
2587 {
2588         if (!paragraphVisible(dit))
2589                 return Point(-1, -1);
2590
2591         CursorSlice const & bot = dit.bottom();
2592         TextMetrics const & tm = textMetrics(bot.text());
2593
2594         Point p = coordOffset(dit, boundary); // offset from outer paragraph
2595         p.y_ += tm.parMetrics(bot.pit()).position();
2596         return p;
2597 }
2598
2599
2600 bool BufferView::paragraphVisible(DocIterator const & dit) const
2601 {
2602         CursorSlice const & bot = dit.bottom();
2603         TextMetrics const & tm = textMetrics(bot.text());
2604
2605         return tm.contains(bot.pit());
2606 }
2607
2608
2609 void BufferView::cursorPosAndHeight(Point & p, int & h) const
2610 {
2611         Cursor const & cur = cursor();
2612         Font const font = cur.getFont();
2613         frontend::FontMetrics const & fm = theFontMetrics(font);
2614         int const asc = fm.maxAscent();
2615         int const des = fm.maxDescent();
2616         h = asc + des;
2617         p = getPos(cur, cur.boundary());
2618         p.y_ -= asc;
2619 }
2620
2621
2622 bool BufferView::cursorInView(Point const & p, int h) const
2623 {
2624         Cursor const & cur = cursor();
2625         // does the cursor touch the screen ?
2626         if (p.y_ + h < 0 || p.y_ >= workHeight() || !paragraphVisible(cur))
2627                 return false;
2628         return true;
2629 }
2630
2631
2632 void BufferView::draw(frontend::Painter & pain)
2633 {
2634         if (height_ == 0 || width_ == 0)
2635                 return;
2636         LYXERR(Debug::PAINTING, "\t\t*** START DRAWING ***");
2637
2638         Text & text = buffer_.text();
2639         TextMetrics const & tm = d->text_metrics_[&text];
2640         int const y = tm.first().second->position();
2641         PainterInfo pi(this, pain);
2642
2643         switch (d->update_strategy_) {
2644
2645         case NoScreenUpdate:
2646                 // If no screen painting is actually needed, only some the different
2647                 // coordinates of insets and paragraphs needs to be updated.
2648                 pi.full_repaint = true;
2649                 pi.pain.setDrawingEnabled(false);
2650                 tm.draw(pi, 0, y);
2651                 break;
2652
2653         case SingleParUpdate:
2654                 pi.full_repaint = false;
2655                 // In general, only the current row of the outermost paragraph
2656                 // will be redrawn. Particular cases where selection spans
2657                 // multiple paragraph are correctly detected in TextMetrics.
2658                 tm.draw(pi, 0, y);
2659                 break;
2660
2661         case DecorationUpdate:
2662                 // FIXME: We should also distinguish DecorationUpdate to avoid text
2663                 // drawing if possible. This is not possible to do easily right now
2664                 // because of the single backing pixmap.
2665
2666         case FullScreenUpdate:
2667                 // The whole screen, including insets, will be refreshed.
2668                 pi.full_repaint = true;
2669
2670                 // Clear background.
2671                 pain.fillRectangle(0, 0, width_, height_,
2672                         pi.backgroundColor(&buffer_.inset()));
2673
2674                 // Draw everything.
2675                 tm.draw(pi, 0, y);
2676
2677                 // and possibly grey out below
2678                 pair<pit_type, ParagraphMetrics const *> lastpm = tm.last();
2679                 int const y2 = lastpm.second->position() + lastpm.second->descent();
2680                 
2681                 if (y2 < height_) {
2682                         Color color = buffer().isInternal() 
2683                                 ? Color_background : Color_bottomarea;
2684                         pain.fillRectangle(0, y2, width_, height_ - y2, color);
2685                 }
2686                 break;
2687         }
2688         LYXERR(Debug::PAINTING, "\n\t\t*** END DRAWING  ***");
2689
2690         // The scrollbar needs an update.
2691         updateScrollbar();
2692
2693         // Normalize anchor for next time
2694         pair<pit_type, ParagraphMetrics const *> firstpm = tm.first();
2695         pair<pit_type, ParagraphMetrics const *> lastpm = tm.last();
2696         for (pit_type pit = firstpm.first; pit <= lastpm.first; ++pit) {
2697                 ParagraphMetrics const & pm = tm.parMetrics(pit);
2698                 if (pm.position() + pm.descent() > 0) {
2699                         d->anchor_pit_ = pit;
2700                         d->anchor_ypos_ = pm.position();
2701                         break;
2702                 }
2703         }
2704         LYXERR(Debug::PAINTING, "Found new anchor pit = " << d->anchor_pit_
2705                 << "  anchor ypos = " << d->anchor_ypos_);
2706 }
2707
2708
2709 void BufferView::message(docstring const & msg)
2710 {
2711         if (d->gui_)
2712                 d->gui_->message(msg);
2713 }
2714
2715
2716 void BufferView::showDialog(string const & name)
2717 {
2718         if (d->gui_)
2719                 d->gui_->showDialog(name, string());
2720 }
2721
2722
2723 void BufferView::showDialog(string const & name,
2724         string const & data, Inset * inset)
2725 {
2726         if (d->gui_)
2727                 d->gui_->showDialog(name, data, inset);
2728 }
2729
2730
2731 void BufferView::updateDialog(string const & name, string const & data)
2732 {
2733         if (d->gui_)
2734                 d->gui_->updateDialog(name, data);
2735 }
2736
2737
2738 void BufferView::setGuiDelegate(frontend::GuiBufferViewDelegate * gui)
2739 {
2740         d->gui_ = gui;
2741 }
2742
2743
2744 // FIXME: Move this out of BufferView again
2745 docstring BufferView::contentsOfPlaintextFile(FileName const & fname)
2746 {
2747         if (!fname.isReadableFile()) {
2748                 docstring const error = from_ascii(strerror(errno));
2749                 docstring const file = makeDisplayPath(fname.absFilename(), 50);
2750                 docstring const text =
2751                   bformat(_("Could not read the specified document\n"
2752                             "%1$s\ndue to the error: %2$s"), file, error);
2753                 Alert::error(_("Could not read file"), text);
2754                 return docstring();
2755         }
2756
2757         if (!fname.isReadableFile()) {
2758                 docstring const file = makeDisplayPath(fname.absFilename(), 50);
2759                 docstring const text =
2760                   bformat(_("%1$s\n is not readable."), file);
2761                 Alert::error(_("Could not open file"), text);
2762                 return docstring();
2763         }
2764
2765         // FIXME UNICODE: We don't know the encoding of the file
2766         docstring file_content = fname.fileContents("UTF-8");
2767         if (file_content.empty()) {
2768                 Alert::error(_("Reading not UTF-8 encoded file"),
2769                              _("The file is not UTF-8 encoded.\n"
2770                                "It will be read as local 8Bit-encoded.\n"
2771                                "If this does not give the correct result\n"
2772                                "then please change the encoding of the file\n"
2773                                "to UTF-8 with a program other than LyX.\n"));
2774                 file_content = fname.fileContents("local8bit");
2775         }
2776
2777         return normalize_c(file_content);
2778 }
2779
2780
2781 void BufferView::insertPlaintextFile(FileName const & f, bool asParagraph)
2782 {
2783         docstring const tmpstr = contentsOfPlaintextFile(f);
2784
2785         if (tmpstr.empty())
2786                 return;
2787
2788         Cursor & cur = cursor();
2789         cap::replaceSelection(cur);
2790         buffer_.undo().recordUndo(cur);
2791         if (asParagraph)
2792                 cur.innerText()->insertStringAsParagraphs(cur, tmpstr, cur.current_font);
2793         else
2794                 cur.innerText()->insertStringAsLines(cur, tmpstr, cur.current_font);
2795
2796         buffer_.changed(true);
2797 }
2798
2799
2800 docstring const & BufferView::inlineCompletion() const
2801 {
2802         return d->inlineCompletion_;
2803 }
2804
2805
2806 size_t const & BufferView::inlineCompletionUniqueChars() const
2807 {
2808         return d->inlineCompletionUniqueChars_;
2809 }
2810
2811
2812 DocIterator const & BufferView::inlineCompletionPos() const
2813 {
2814         return d->inlineCompletionPos_;
2815 }
2816
2817
2818 bool samePar(DocIterator const & a, DocIterator const & b)
2819 {
2820         if (a.empty() && b.empty())
2821                 return true;
2822         if (a.empty() || b.empty())
2823                 return false;
2824         if (a.depth() != b.depth())
2825                 return false;
2826         return &a.innerParagraph() == &b.innerParagraph();
2827 }
2828
2829
2830 void BufferView::setInlineCompletion(Cursor & cur, DocIterator const & pos, 
2831         docstring const & completion, size_t uniqueChars)
2832 {
2833         uniqueChars = min(completion.size(), uniqueChars);
2834         bool changed = d->inlineCompletion_ != completion
2835                 || d->inlineCompletionUniqueChars_ != uniqueChars;
2836         bool singlePar = true;
2837         d->inlineCompletion_ = completion;
2838         d->inlineCompletionUniqueChars_ = min(completion.size(), uniqueChars);
2839         
2840         //lyxerr << "setInlineCompletion pos=" << pos << " completion=" << completion << " uniqueChars=" << uniqueChars << std::endl;
2841         
2842         // at new position?
2843         DocIterator const & old = d->inlineCompletionPos_;
2844         if (old != pos) {
2845                 //lyxerr << "inlineCompletionPos changed" << std::endl;
2846                 // old or pos are in another paragraph?
2847                 if ((!samePar(cur, pos) && !pos.empty())
2848                     || (!samePar(cur, old) && !old.empty())) {
2849                         singlePar = false;
2850                         //lyxerr << "different paragraph" << std::endl;
2851                 }
2852                 d->inlineCompletionPos_ = pos;
2853         }
2854         
2855         // set update flags
2856         if (changed) {
2857                 if (singlePar && !(cur.disp_.update() & Update::Force))
2858                         cur.updateFlags(cur.disp_.update() | Update::SinglePar);
2859                 else
2860                         cur.updateFlags(cur.disp_.update() | Update::Force);
2861         }
2862 }
2863
2864 } // namespace lyx