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