]> git.lyx.org Git - lyx.git/blob - src/BufferView.cpp
* GuiDocument.cpp: before accessing the buffer() in paramsToDialog(), check
[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(false);
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(false);
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(false);
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(false);
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                 buffer_.changed(true);
577                 return;
578         }
579
580         // cut off at the top
581         if (value <= d->scrollbarParameters_.min) {
582                 DocIterator dit = doc_iterator_begin(&buffer_);
583                 showCursor(dit);
584                 LYXERR(Debug::SCROLLING, "scroll to top");
585                 return;
586         }
587
588         // cut off at the bottom
589         if (value >= d->scrollbarParameters_.max) {
590                 DocIterator dit = doc_iterator_end(&buffer_);
591                 dit.backwardPos();
592                 showCursor(dit);
593                 LYXERR(Debug::SCROLLING, "scroll to bottom");
594                 return;
595         }
596
597         // find paragraph at target position
598         int par_pos = d->scrollbarParameters_.min;
599         pit_type i = 0;
600         for (; i != int(d->par_height_.size()); ++i) {
601                 par_pos += d->par_height_[i];
602                 if (par_pos >= value)
603                         break;
604         }
605
606         if (par_pos < value) {
607                 // It seems we didn't find the correct pit so stay on the safe side and
608                 // scroll to bottom.
609                 LYXERR0("scrolling position not found!");
610                 scrollDocView(d->scrollbarParameters_.max);
611                 return;
612         }
613
614         DocIterator dit = doc_iterator_begin(&buffer_);
615         dit.pit() = i;
616         LYXERR(Debug::SCROLLING, "value = " << value << " -> scroll to pit " << i);
617         showCursor(dit);
618 }
619
620
621 // FIXME: this method is not working well.
622 void BufferView::setCursorFromScrollbar()
623 {
624         TextMetrics & tm = d->text_metrics_[&buffer_.text()];
625
626         int const height = 2 * defaultRowHeight();
627         int const first = height;
628         int const last = height_ - height;
629         int newy = 0;
630         Cursor const & oldcur = d->cursor_;
631
632         switch (cursorStatus(oldcur)) {
633         case CUR_ABOVE:
634                 newy = first;
635                 break;
636         case CUR_BELOW:
637                 newy = last;
638                 break;
639         case CUR_INSIDE:
640                 int const y = getPos(oldcur, oldcur.boundary()).y_;
641                 newy = min(last, max(y, first));
642                 if (y == newy) 
643                         return;
644         }
645         // We reset the cursor because cursorStatus() does not
646         // work when the cursor is within mathed.
647         Cursor cur(*this);
648         cur.reset();
649         tm.setCursorFromCoordinates(cur, 0, newy);
650
651         // update the bufferview cursor and notify insets
652         // FIXME: Care about the d->cursor_ flags to redraw if needed
653         Cursor old = d->cursor_;
654         mouseSetCursor(cur);
655         bool badcursor = notifyCursorLeavesOrEnters(old, d->cursor_);
656         if (badcursor)
657                 d->cursor_.fixIfBroken();
658 }
659
660
661 Change const BufferView::getCurrentChange() const
662 {
663         if (!d->cursor_.selection())
664                 return Change(Change::UNCHANGED);
665
666         DocIterator dit = d->cursor_.selectionBegin();
667         return dit.paragraph().lookupChange(dit.pos());
668 }
669
670
671 // this could be used elsewhere as well?
672 // FIXME: This does not work within mathed!
673 CursorStatus BufferView::cursorStatus(DocIterator const & dit) const
674 {
675         Point const p = getPos(dit, dit.boundary());
676         if (p.y_ < 0)
677                 return CUR_ABOVE;
678         if (p.y_ > workHeight())
679                 return CUR_BELOW;
680         return CUR_INSIDE;
681 }
682
683
684 void BufferView::bookmarkEditPosition()
685 {
686         // Don't eat cpu time for each keystroke
687         if (d->cursor_.paragraph().id() == d->bookmark_edit_position_)
688                 return;
689         saveBookmark(0);
690         d->bookmark_edit_position_ = d->cursor_.paragraph().id();
691 }
692
693
694 void BufferView::saveBookmark(unsigned int idx)
695 {
696         // tentatively save bookmark, id and pos will be used to
697         // acturately locate a bookmark in a 'live' lyx session.
698         // pit and pos will be updated with bottom level pit/pos
699         // when lyx exits.
700         theSession().bookmarks().save(
701                 buffer_.fileName(),
702                 d->cursor_.bottom().pit(),
703                 d->cursor_.bottom().pos(),
704                 d->cursor_.paragraph().id(),
705                 d->cursor_.pos(),
706                 idx
707         );
708         if (idx)
709                 // emit message signal.
710                 message(_("Save bookmark"));
711 }
712
713
714 bool BufferView::moveToPosition(pit_type bottom_pit, pos_type bottom_pos,
715         int top_id, pos_type top_pos)
716 {
717         bool success = false;
718         DocIterator dit;
719
720         d->cursor_.clearSelection();
721
722         // if a valid par_id is given, try it first
723         // This is the case for a 'live' bookmark when unique paragraph ID
724         // is used to track bookmarks.
725         if (top_id > 0) {
726                 dit = buffer_.getParFromID(top_id);
727                 if (!dit.atEnd()) {
728                         dit.pos() = min(dit.paragraph().size(), top_pos);
729                         // Some slices of the iterator may not be
730                         // reachable (e.g. closed collapsable inset)
731                         // so the dociterator may need to be
732                         // shortened. Otherwise, setCursor may crash
733                         // lyx when the cursor can not be set to these
734                         // insets.
735                         size_t const n = dit.depth();
736                         for (size_t i = 0; i < n; ++i)
737                                 if (!dit[i].inset().editable()) {
738                                         dit.resize(i);
739                                         break;
740                                 }
741                         success = true;
742                 }
743         }
744
745         // if top_id == 0, or searching through top_id failed
746         // This is the case for a 'restored' bookmark when only bottom
747         // (document level) pit was saved. Because of this, bookmark
748         // restoration is inaccurate. If a bookmark was within an inset,
749         // it will be restored to the left of the outmost inset that contains
750         // the bookmark.
751         if (bottom_pit < int(buffer_.paragraphs().size())) {
752                 dit = doc_iterator_begin(&buffer_);
753                                 
754                 dit.pit() = bottom_pit;
755                 dit.pos() = min(bottom_pos, dit.paragraph().size());
756                 success = true;
757         }
758
759         if (success) {
760                 // Note: only bottom (document) level pit is set.
761                 setCursor(dit);
762                 // set the current font.
763                 d->cursor_.setCurrentFont();
764                 // To center the screen on this new position we need the
765                 // paragraph position which is computed at draw() time.
766                 // So we need a redraw!
767                 buffer_.changed(false);
768                 if (fitCursor())
769                         showCursor();
770         }
771
772         return success;
773 }
774
775
776 void BufferView::translateAndInsert(char_type c, Text * t, Cursor & cur)
777 {
778         if (lyxrc.rtl_support) {
779                 if (d->cursor_.real_current_font.isRightToLeft()) {
780                         if (d->intl_.keymap == Intl::PRIMARY)
781                                 d->intl_.keyMapSec();
782                 } else {
783                         if (d->intl_.keymap == Intl::SECONDARY)
784                                 d->intl_.keyMapPrim();
785                 }
786         }
787
788         d->intl_.getTransManager().translateAndInsert(c, t, cur);
789 }
790
791
792 int BufferView::workWidth() const
793 {
794         return width_;
795 }
796
797
798 void BufferView::recenter()
799 {
800         showCursor(d->cursor_, true);
801 }
802
803
804 void BufferView::showCursor()
805 {
806         showCursor(d->cursor_, false);
807 }
808
809
810 void BufferView::showCursor(DocIterator const & dit, bool recenter)
811 {
812         if (scrollToCursor(dit, recenter))
813                 buffer_.changed(false);
814 }
815
816
817 void BufferView::scrollToCursor()
818 {
819         scrollToCursor(d->cursor_, false);
820 }
821
822
823 bool BufferView::scrollToCursor(DocIterator const & dit, bool recenter)
824 {
825         // We are not properly started yet, delay until resizing is
826         // done.
827         if (height_ == 0)
828                 return false;
829
830         LYXERR(Debug::SCROLLING, "recentering!");
831
832         CursorSlice const & bot = dit.bottom();
833         TextMetrics & tm = d->text_metrics_[bot.text()];
834
835         pos_type const max_pit = pos_type(bot.text()->paragraphs().size() - 1);
836         int bot_pit = bot.pit();
837         if (bot_pit > max_pit) {
838                 // FIXME: Why does this happen?
839                 LYXERR0("bottom pit is greater that max pit: "
840                         << bot_pit << " > " << max_pit);
841                 bot_pit = max_pit;
842         }
843
844         if (bot_pit == tm.first().first - 1)
845                 tm.newParMetricsUp();
846         else if (bot_pit == tm.last().first + 1)
847                 tm.newParMetricsDown();
848
849         if (tm.contains(bot_pit)) {
850                 ParagraphMetrics const & pm = tm.parMetrics(bot_pit);
851                 LASSERT(!pm.rows().empty(), /**/);
852                 // FIXME: smooth scrolling doesn't work in mathed.
853                 CursorSlice const & cs = dit.innerTextSlice();
854                 int offset = coordOffset(dit, dit.boundary()).y_;
855                 int ypos = pm.position() + offset;
856                 Dimension const & row_dim =
857                         pm.getRow(cs.pos(), dit.boundary()).dimension();
858                 int scrolled = 0;
859                 if (recenter)
860                         scrolled = scroll(ypos - height_/2);
861                 else if (ypos - row_dim.ascent() < 0)
862                         scrolled = scrollUp(- ypos + row_dim.ascent());
863                 else if (ypos + row_dim.descent() > height_)
864                         scrolled = scrollDown(ypos - height_ + defaultRowHeight() ); 
865
866                 // else, nothing to do, the cursor is already visible so we just return.
867                 if (scrolled != 0) {
868                         updateMetrics();
869                         return true;
870                 }
871                 return false;
872         }
873
874         // fix inline completion position
875         if (d->inlineCompletionPos_.fixIfBroken())
876                 d->inlineCompletionPos_ = DocIterator();
877
878         tm.redoParagraph(bot_pit);
879         ParagraphMetrics const & pm = tm.parMetrics(bot_pit);
880         int offset = coordOffset(dit, dit.boundary()).y_;
881
882         d->anchor_pit_ = bot_pit;
883         CursorSlice const & cs = dit.innerTextSlice();
884         Dimension const & row_dim =
885                 pm.getRow(cs.pos(), dit.boundary()).dimension();
886
887         if (recenter)
888                 d->anchor_ypos_ = height_/2;
889         else if (d->anchor_pit_ == 0)
890                 d->anchor_ypos_ = offset + pm.ascent();
891         else if (d->anchor_pit_ == max_pit)
892                 d->anchor_ypos_ = height_ - offset - row_dim.descent();
893         else if (offset > height_)
894                 d->anchor_ypos_ = height_ - offset - defaultRowHeight();
895         else
896                 d->anchor_ypos_ = defaultRowHeight() * 2;
897
898         updateMetrics();
899         return true;
900 }
901
902
903 void BufferView::updateLayout(DocumentClass const * const oldlayout)
904 {
905         message(_("Converting document to new document class..."));
906         
907         StableDocIterator backcur(d->cursor_);
908         ErrorList & el = buffer_.errorList("Class Switch");
909         cap::switchBetweenClasses(
910                         oldlayout, buffer_.params().documentClassPtr(),
911                         static_cast<InsetText &>(buffer_.inset()), el);
912
913         setCursor(backcur.asDocIterator(&buffer_));
914
915         buffer_.errors("Class Switch");
916         buffer_.updateLabels();
917 }
918
919 /** Return the change status at cursor position, taking in account the
920  * status at each level of the document iterator (a table in a deleted
921  * footnote is deleted).
922  * When \param outer is true, the top slice is not looked at.
923  */
924 static Change::Type lookupChangeType(DocIterator const & dit, bool outer = false)
925 {
926         size_t const depth = dit.depth() - (outer ? 1 : 0);
927
928         for (size_t i = 0 ; i < depth ; ++i) {
929                 CursorSlice const & slice = dit[i];
930                 if (!slice.inset().inMathed()
931                     && slice.pos() < slice.paragraph().size()) {
932                         Change::Type const ch = slice.paragraph().lookupChange(slice.pos()).type;
933                         if (ch != Change::UNCHANGED)
934                                 return ch;
935                 }
936         }
937         return Change::UNCHANGED;
938 }
939
940
941 bool BufferView::getStatus(FuncRequest const & cmd, FuncStatus & flag)
942 {
943         // Can we use a readonly buffer?
944         if (buffer_.isReadonly()
945             && !lyxaction.funcHasFlag(cmd.action, LyXAction::ReadOnly)
946             && !lyxaction.funcHasFlag(cmd.action, LyXAction::NoBuffer)) {
947                 flag.message(from_utf8(N_("Document is read-only")));
948                 flag.setEnabled(false);
949                 return true;
950         }
951         // Are we in a DELETED change-tracking region?
952         if (lookupChangeType(d->cursor_, true) == Change::DELETED
953             && !lyxaction.funcHasFlag(cmd.action, LyXAction::ReadOnly)
954             && !lyxaction.funcHasFlag(cmd.action, LyXAction::NoBuffer)) {
955                 flag.message(from_utf8(N_("This portion of the document is deleted.")));
956                 flag.setEnabled(false);
957                 return true;
958         }
959
960         Cursor & cur = d->cursor_;
961
962         if (cur.getStatus(cmd, flag))
963                 return true;
964
965         switch (cmd.action) {
966
967         // FIXME: This is a bit problematic because we don't check is this is a
968         // document BufferView or not for these LFUNs. We probably have to
969         // dispatch both to currentBufferView() and, if that fails,
970         // to documentBufferView(); same as we do know for current Buffer and
971         // document Buffer. Ideally those LFUN should go to Buffer as they*
972         // operate on the full Buffer and the cursor is only needed either for
973         // an Undo record or to restore a cursor position. But we don't know
974         // how to do that inside Buffer of course.
975         case LFUN_BUFFER_PARAMS_APPLY:
976         case LFUN_LAYOUT_MODULES_CLEAR:
977         case LFUN_LAYOUT_MODULE_ADD:
978         case LFUN_LAYOUT_RELOAD:
979         case LFUN_TEXTCLASS_APPLY:
980         case LFUN_TEXTCLASS_LOAD:
981                 flag.setEnabled(!buffer_.isReadonly());
982                 break;
983
984         case LFUN_UNDO:
985                 flag.setEnabled(buffer_.undo().hasUndoStack());
986                 break;
987         case LFUN_REDO:
988                 flag.setEnabled(buffer_.undo().hasRedoStack());
989                 break;
990         case LFUN_FILE_INSERT:
991         case LFUN_FILE_INSERT_PLAINTEXT_PARA:
992         case LFUN_FILE_INSERT_PLAINTEXT:
993         case LFUN_BOOKMARK_SAVE:
994                 // FIXME: Actually, these LFUNS should be moved to Text
995                 flag.setEnabled(cur.inTexted());
996                 break;
997
998         case LFUN_FONT_STATE:
999         case LFUN_LABEL_INSERT:
1000         case LFUN_INFO_INSERT:
1001         case LFUN_INSET_EDIT:
1002         case LFUN_PARAGRAPH_GOTO:
1003         case LFUN_NOTE_NEXT:
1004         case LFUN_REFERENCE_NEXT:
1005         case LFUN_WORD_FIND:
1006         case LFUN_WORD_FIND_FORWARD:
1007         case LFUN_WORD_FIND_BACKWARD:
1008         case LFUN_WORD_FINDADV:
1009         case LFUN_WORD_REPLACE:
1010         case LFUN_MARK_OFF:
1011         case LFUN_MARK_ON:
1012         case LFUN_MARK_TOGGLE:
1013         case LFUN_SCREEN_RECENTER:
1014         case LFUN_SCREEN_SHOW_CURSOR:
1015         case LFUN_BIBTEX_DATABASE_ADD:
1016         case LFUN_BIBTEX_DATABASE_DEL:
1017         case LFUN_ALL_INSETS_TOGGLE:
1018         case LFUN_STATISTICS:
1019         case LFUN_BRANCH_ADD_INSERT:
1020         case LFUN_KEYMAP_OFF:
1021         case LFUN_KEYMAP_PRIMARY:
1022         case LFUN_KEYMAP_SECONDARY:
1023         case LFUN_KEYMAP_TOGGLE:
1024                 flag.setEnabled(true);
1025                 break;
1026
1027         case LFUN_REGEXP_MODE:
1028                 flag.setEnabled(buffer().isInternal() && !cur.inRegexped()
1029                                 && cur.inset().lyxCode() != ERT_CODE);
1030                 break;
1031
1032         case LFUN_LABEL_COPY_AS_REF: {
1033                 // if there is an inset at cursor, see whether it
1034                 // handles the lfun
1035                 Inset * inset = cur.nextInset();
1036                 if (!inset || !inset->getStatus(cur, cmd, flag))
1037                         flag.setEnabled(false);
1038                 break;
1039         }
1040
1041         case LFUN_LABEL_GOTO: {
1042                 flag.setEnabled(!cmd.argument().empty()
1043                     || getInsetByCode<InsetRef>(cur, REF_CODE));
1044                 break;
1045         }
1046
1047         case LFUN_CHANGES_TRACK:
1048                 flag.setEnabled(true);
1049                 flag.setOnOff(buffer_.params().trackChanges);
1050                 break;
1051
1052         case LFUN_CHANGES_OUTPUT:
1053                 flag.setEnabled(true);
1054                 flag.setOnOff(buffer_.params().outputChanges);
1055                 break;
1056
1057         case LFUN_CHANGES_MERGE:
1058         case LFUN_CHANGE_NEXT:
1059         case LFUN_CHANGE_PREVIOUS:
1060         case LFUN_ALL_CHANGES_ACCEPT:
1061         case LFUN_ALL_CHANGES_REJECT:
1062                 // TODO: context-sensitive enabling of LFUNs
1063                 // In principle, these command should only be enabled if there
1064                 // is a change in the document. However, without proper
1065                 // optimizations, this will inevitably result in poor performance.
1066                 flag.setEnabled(true);
1067                 break;
1068
1069         case LFUN_BUFFER_TOGGLE_COMPRESSION: {
1070                 flag.setOnOff(buffer_.params().compressed);
1071                 break;
1072         }
1073         
1074         case LFUN_SCREEN_UP:
1075         case LFUN_SCREEN_DOWN:
1076         case LFUN_SCROLL:
1077         case LFUN_SCREEN_UP_SELECT:
1078         case LFUN_SCREEN_DOWN_SELECT:
1079         case LFUN_INSET_FORALL:
1080                 flag.setEnabled(true);
1081                 break;
1082
1083         case LFUN_LAYOUT_TABULAR:
1084                 flag.setEnabled(cur.innerInsetOfType(TABULAR_CODE));
1085                 break;
1086
1087         case LFUN_LAYOUT:
1088                 flag.setEnabled(!cur.inset().forcePlainLayout(cur.idx()));
1089                 break;
1090
1091         case LFUN_LAYOUT_PARAGRAPH:
1092                 flag.setEnabled(cur.inset().allowParagraphCustomization(cur.idx()));
1093                 break;
1094
1095         case LFUN_DIALOG_SHOW_NEW_INSET:
1096                 // FIXME: this is wrong, but I do not understand the
1097                 // intent (JMarc)
1098                 if (cur.inset().lyxCode() == CAPTION_CODE)
1099                         return cur.inset().getStatus(cur, cmd, flag);
1100                 // FIXME we should consider passthru paragraphs too.
1101                 flag.setEnabled(!cur.inset().getLayout().isPassThru());
1102                 break;
1103
1104         case LFUN_CITATION_INSERT: {
1105                 FuncRequest fr(LFUN_INSET_INSERT, "citation");
1106                 // FIXME: This could turn in a recursive hell.
1107                 // Shouldn't we use Buffer::getStatus() instead?
1108                 flag.setEnabled(lyx::getStatus(fr).enabled());
1109                 break;
1110         }
1111         case LFUN_INSET_APPLY: {
1112                 string const name = cmd.getArg(0);
1113                 Inset * inset = editedInset(name);
1114                 if (inset) {
1115                         FuncRequest fr(LFUN_INSET_MODIFY, cmd.argument());
1116                         FuncStatus fs;
1117                         if (!inset->getStatus(cur, fr, fs)) {
1118                                 // Every inset is supposed to handle this
1119                                 LASSERT(false, break);
1120                         }
1121                         flag |= fs;
1122                 } else {
1123                         FuncRequest fr(LFUN_INSET_INSERT, cmd.argument());
1124                         flag |= lyx::getStatus(fr);
1125                 }
1126                 break;
1127         }
1128
1129         default:
1130                 flag.setEnabled(false);
1131                 return false;
1132         }
1133
1134         return true;
1135 }
1136
1137
1138 Inset * BufferView::editedInset(string const & name) const
1139 {
1140         map<string, Inset *>::const_iterator it = d->edited_insets_.find(name);
1141         return it == d->edited_insets_.end() ? 0 : it->second;
1142 }
1143
1144
1145 void BufferView::editInset(string const & name, Inset * inset)
1146 {
1147         d->edited_insets_[name] = inset;
1148 }
1149
1150
1151 void BufferView::dispatch(FuncRequest const & cmd, DispatchResult & dr)
1152 {
1153         //lyxerr << [ cmd = " << cmd << "]" << endl;
1154
1155         // Make sure that the cached BufferView is correct.
1156         LYXERR(Debug::ACTION, " action[" << cmd.action << ']'
1157                 << " arg[" << to_utf8(cmd.argument()) << ']'
1158                 << " x[" << cmd.x << ']'
1159                 << " y[" << cmd.y << ']'
1160                 << " button[" << cmd.button() << ']');
1161
1162         string const argument = to_utf8(cmd.argument());
1163         Cursor & cur = d->cursor_;
1164
1165         // Don't dispatch function that does not apply to internal buffers.
1166         if (buffer_.isInternal() 
1167             && lyxaction.funcHasFlag(cmd.action, LyXAction::NoInternal))
1168                 return;
1169
1170         // We'll set this back to false if need be.
1171         bool dispatched = true;
1172         buffer_.undo().beginUndoGroup();
1173
1174         switch (cmd.action) {
1175
1176         case LFUN_BUFFER_PARAMS_APPLY: {
1177                 DocumentClass const * const oldClass = buffer_.params().documentClassPtr();
1178                 cur.recordUndoFullDocument();
1179                 istringstream ss(to_utf8(cmd.argument()));
1180                 Lexer lex;
1181                 lex.setStream(ss);
1182                 int const unknown_tokens = buffer_.readHeader(lex);
1183                 if (unknown_tokens != 0) {
1184                         LYXERR0("Warning in LFUN_BUFFER_PARAMS_APPLY!\n"
1185                                                 << unknown_tokens << " unknown token"
1186                                                 << (unknown_tokens == 1 ? "" : "s"));
1187                 }
1188                 updateLayout(oldClass);
1189                         
1190                 // We are most certainly here because of a change in the document
1191                 // It is then better to make sure that all dialogs are in sync with
1192                 // current document settings.
1193                 dr.update(Update::Force | Update::FitCursor);
1194                 break;
1195         }
1196                 
1197         case LFUN_LAYOUT_MODULES_CLEAR: {
1198                 DocumentClass const * const oldClass =
1199                         buffer_.params().documentClassPtr();
1200                 cur.recordUndoFullDocument();
1201                 buffer_.params().clearLayoutModules();
1202                 buffer_.params().makeDocumentClass();
1203                 updateLayout(oldClass);
1204                 dr.update(Update::Force | Update::FitCursor);
1205                 break;
1206         }
1207
1208         case LFUN_LAYOUT_MODULE_ADD: {
1209                 BufferParams const & params = buffer_.params();
1210                 if (!params.moduleCanBeAdded(argument)) {
1211                         LYXERR0("Module `" << argument << 
1212                                 "' cannot be added due to failed requirements or "
1213                                 "conflicts with installed modules.");
1214                         break;
1215                 }
1216                 DocumentClass const * const oldClass = params.documentClassPtr();
1217                 cur.recordUndoFullDocument();
1218                 buffer_.params().addLayoutModule(argument);
1219                 buffer_.params().makeDocumentClass();
1220                 updateLayout(oldClass);
1221                 dr.update(Update::Force | Update::FitCursor);
1222                 break;
1223         }
1224
1225         case LFUN_TEXTCLASS_APPLY: {
1226                 if (!LayoutFileList::get().load(argument, buffer_.temppath()) &&
1227                         !LayoutFileList::get().load(argument, buffer_.filePath()))
1228                         break;
1229
1230                 LayoutFile const * old_layout = buffer_.params().baseClass();
1231                 LayoutFile const * new_layout = &(LayoutFileList::get()[argument]);
1232
1233                 if (old_layout == new_layout)
1234                         // nothing to do
1235                         break;
1236
1237                 //Save the old, possibly modular, layout for use in conversion.
1238                 DocumentClass const * const oldDocClass =
1239                         buffer_.params().documentClassPtr();
1240                 cur.recordUndoFullDocument();
1241                 buffer_.params().setBaseClass(argument);
1242                 buffer_.params().makeDocumentClass();
1243                 updateLayout(oldDocClass);
1244                 dr.update(Update::Force | Update::FitCursor);
1245                 break;
1246         }
1247
1248         case LFUN_TEXTCLASS_LOAD:
1249                 LayoutFileList::get().load(argument, buffer_.temppath()) ||
1250                 LayoutFileList::get().load(argument, buffer_.filePath());
1251                 break;
1252
1253         case LFUN_LAYOUT_RELOAD: {
1254                 DocumentClass const * const oldClass = buffer_.params().documentClassPtr();
1255                 LayoutFileIndex bc = buffer_.params().baseClassID();
1256                 LayoutFileList::get().reset(bc);
1257                 buffer_.params().setBaseClass(bc);
1258                 buffer_.params().makeDocumentClass();
1259                 updateLayout(oldClass);
1260                 dr.update(Update::Force | Update::FitCursor);
1261                 break;
1262         }
1263
1264         case LFUN_UNDO:
1265                 dr.setMessage(_("Undo"));
1266                 cur.clearSelection();
1267                 if (!cur.textUndo())
1268                         dr.setMessage(_("No further undo information"));
1269                 else
1270                         dr.update(Update::Force | Update::FitCursor);
1271                 break;
1272
1273         case LFUN_REDO:
1274                 dr.setMessage(_("Redo"));
1275                 cur.clearSelection();
1276                 if (!cur.textRedo())
1277                         dr.setMessage(_("No further redo information"));
1278                 else
1279                         dr.update(Update::Force | Update::FitCursor);
1280                 break;
1281
1282         case LFUN_FONT_STATE:
1283                 dr.setMessage(cur.currentState());
1284                 break;
1285
1286         case LFUN_BOOKMARK_SAVE:
1287                 saveBookmark(convert<unsigned int>(to_utf8(cmd.argument())));
1288                 break;
1289
1290         case LFUN_LABEL_GOTO: {
1291                 docstring label = cmd.argument();
1292                 if (label.empty()) {
1293                         InsetRef * inset =
1294                                 getInsetByCode<InsetRef>(cur, REF_CODE);
1295                         if (inset) {
1296                                 label = inset->getParam("reference");
1297                                 // persistent=false: use temp_bookmark
1298                                 saveBookmark(0);
1299                         }
1300                 }
1301                 if (!label.empty())
1302                         gotoLabel(label);
1303                 break;
1304         }
1305         
1306         case LFUN_INSET_EDIT: {
1307                 FuncRequest fr(cmd);
1308                 // if there is an inset at cursor, see whether it
1309                 // can be modified.
1310                 Inset * inset = cur.nextInset();
1311                 if (inset)
1312                         inset->dispatch(cur, fr);
1313                 // if it did not work, try the underlying inset.
1314                 if (!inset || !cur.result().dispatched())
1315                         cur.dispatch(cmd);
1316
1317                 // FIXME I'm adding the last break to solve a crash,
1318                 // but that is obviously not right.
1319                 if (!cur.result().dispatched())
1320                         // It did not work too; no action needed.
1321                         break;
1322                 break;
1323         }
1324
1325         case LFUN_PARAGRAPH_GOTO: {
1326                 int const id = convert<int>(cmd.getArg(0));
1327                 int const pos = convert<int>(cmd.getArg(1));
1328                 int i = 0;
1329                 for (Buffer * b = &buffer_; i == 0 || b != &buffer_;
1330                         b = theBufferList().next(b)) {
1331
1332                         DocIterator dit = b->getParFromID(id);
1333                         if (dit.atEnd()) {
1334                                 LYXERR(Debug::INFO, "No matching paragraph found! [" << id << "].");
1335                                 ++i;
1336                                 continue;
1337                         }
1338                         LYXERR(Debug::INFO, "Paragraph " << dit.paragraph().id()
1339                                 << " found in buffer `"
1340                                 << b->absFileName() << "'.");
1341
1342                         if (b == &buffer_) {
1343                                 // Set the cursor
1344                                 dit.pos() = pos;
1345                                 setCursor(dit);
1346                                 dr.update(Update::Force | Update::FitCursor);
1347                         } else {
1348                                 // Switch to other buffer view and resend cmd
1349                                 theLyXFunc().dispatch(FuncRequest(
1350                                         LFUN_BUFFER_SWITCH, b->absFileName()));
1351                                 theLyXFunc().dispatch(cmd);
1352                         }
1353                         break;
1354                 }
1355                 break;
1356         }
1357
1358         case LFUN_NOTE_NEXT:
1359                 gotoInset(this, NOTE_CODE, false);
1360                 break;
1361
1362         case LFUN_REFERENCE_NEXT: {
1363                 vector<InsetCode> tmp;
1364                 tmp.push_back(LABEL_CODE);
1365                 tmp.push_back(REF_CODE);
1366                 gotoInset(this, tmp, true);
1367                 break;
1368         }
1369
1370         case LFUN_CHANGES_TRACK:
1371                 buffer_.params().trackChanges = !buffer_.params().trackChanges;
1372                 break;
1373
1374         case LFUN_CHANGES_OUTPUT:
1375                 buffer_.params().outputChanges = !buffer_.params().outputChanges;
1376                 if (buffer_.params().outputChanges) {
1377                         bool dvipost    = LaTeXFeatures::isAvailable("dvipost");
1378                         bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
1379                                           LaTeXFeatures::isAvailable("xcolor");
1380
1381                         if (!dvipost && !xcolorulem) {
1382                                 Alert::warning(_("Changes not shown in LaTeX output"),
1383                                                _("Changes will not be highlighted in LaTeX output, "
1384                                                  "because neither dvipost nor xcolor/ulem are installed.\n"
1385                                                  "Please install these packages or redefine "
1386                                                  "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
1387                         } else if (!xcolorulem) {
1388                                 Alert::warning(_("Changes not shown in LaTeX output"),
1389                                                _("Changes will not be highlighted in LaTeX output "
1390                                                  "when using pdflatex, because xcolor and ulem are not installed.\n"
1391                                                  "Please install both packages or redefine "
1392                                                  "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
1393                         }
1394                 }
1395                 break;
1396
1397         case LFUN_CHANGE_NEXT:
1398                 findNextChange(this);
1399                 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1400                 dr.update(Update::Force | Update::FitCursor);
1401                 break;
1402         
1403         case LFUN_CHANGE_PREVIOUS:
1404                 findPreviousChange(this);
1405                 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1406                 dr.update(Update::Force | Update::FitCursor);
1407                 break;
1408
1409         case LFUN_CHANGES_MERGE:
1410                 if (findNextChange(this) || findPreviousChange(this)) {
1411                         dr.update(Update::Force | Update::FitCursor);
1412                         showDialog("changes");
1413                 }
1414                 break;
1415
1416         case LFUN_ALL_CHANGES_ACCEPT:
1417                 // select complete document
1418                 cur.reset();
1419                 cur.selHandle(true);
1420                 buffer_.text().cursorBottom(cur);
1421                 // accept everything in a single step to support atomic undo
1422                 buffer_.text().acceptOrRejectChanges(cur, Text::ACCEPT);
1423                 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1424                 dr.update(Update::Force | Update::FitCursor);
1425                 break;
1426
1427         case LFUN_ALL_CHANGES_REJECT:
1428                 // select complete document
1429                 cur.reset();
1430                 cur.selHandle(true);
1431                 buffer_.text().cursorBottom(cur);
1432                 // reject everything in a single step to support atomic undo
1433                 // Note: reject does not work recursively; the user may have to repeat the operation
1434                 buffer_.text().acceptOrRejectChanges(cur, Text::REJECT);
1435                 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1436                 dr.update(Update::Force | Update::FitCursor);
1437                 break;
1438
1439         case LFUN_WORD_FIND_FORWARD:
1440         case LFUN_WORD_FIND_BACKWARD: {
1441                 static docstring last_search;
1442                 docstring searched_string;
1443
1444                 if (!cmd.argument().empty()) {
1445                         last_search = cmd.argument();
1446                         searched_string = cmd.argument();
1447                 } else {
1448                         searched_string = last_search;
1449                 }
1450
1451                 if (searched_string.empty())
1452                         break;
1453
1454                 bool const fw = cmd.action == LFUN_WORD_FIND_FORWARD;
1455                 docstring const data =
1456                         find2string(searched_string, true, false, fw);
1457                 find(this, FuncRequest(LFUN_WORD_FIND, data));
1458                 break;
1459         }
1460
1461         case LFUN_WORD_FIND: {
1462                 FuncRequest req = cmd;
1463                 if (cmd.argument().empty() && !d->search_request_cache_.argument().empty())
1464                         req = d->search_request_cache_;
1465                 if (req.argument().empty()) {
1466                         theLyXFunc().dispatch(FuncRequest(LFUN_DIALOG_SHOW, "findreplace"));
1467                         break;
1468                 }
1469                 if (find(this, req))
1470                         showCursor();
1471                 else
1472                         message(_("String not found!"));
1473                 d->search_request_cache_ = req;
1474                 break;
1475         }
1476
1477         case LFUN_WORD_REPLACE: {
1478                 bool has_deleted = false;
1479                 if (cur.selection()) {
1480                         DocIterator beg = cur.selectionBegin();
1481                         DocIterator end = cur.selectionEnd();
1482                         if (beg.pit() == end.pit()) {
1483                                 for (pos_type p = beg.pos() ; p < end.pos() ; ++p) {
1484                                         if (!cur.inMathed()
1485                                             && cur.paragraph().isDeleted(p))
1486                                                 has_deleted = true;
1487                                 }
1488                         }
1489                 }
1490                 replace(this, cmd, has_deleted);
1491                 break;
1492         }
1493
1494         case LFUN_WORD_FINDADV: {
1495                 FindAndReplaceOptions opt;
1496                 istringstream iss(to_utf8(cmd.argument()));
1497                 iss >> opt;
1498                 if (findAdv(this, opt))
1499                         cur.dispatched();
1500                 else
1501                         cur.undispatched();
1502                 break;
1503         }
1504
1505         case LFUN_MARK_OFF:
1506                 cur.clearSelection();
1507                 dr.setMessage(from_utf8(N_("Mark off")));
1508                 break;
1509
1510         case LFUN_MARK_ON:
1511                 cur.clearSelection();
1512                 cur.setMark(true);
1513                 dr.setMessage(from_utf8(N_("Mark on")));
1514                 break;
1515
1516         case LFUN_MARK_TOGGLE:
1517                 cur.setSelection(false);
1518                 if (cur.mark()) {
1519                         cur.setMark(false);
1520                         dr.setMessage(from_utf8(N_("Mark removed")));
1521                 } else {
1522                         cur.setMark(true);
1523                         dr.setMessage(from_utf8(N_("Mark set")));
1524                 }
1525                 cur.resetAnchor();
1526                 break;
1527
1528         case LFUN_SCREEN_SHOW_CURSOR:
1529                 showCursor();
1530                 break;
1531         
1532         case LFUN_SCREEN_RECENTER:
1533                 recenter();
1534                 break;
1535
1536         case LFUN_BIBTEX_DATABASE_ADD: {
1537                 Cursor tmpcur = cur;
1538                 findInset(tmpcur, BIBTEX_CODE, false);
1539                 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1540                                                 BIBTEX_CODE);
1541                 if (inset) {
1542                         if (inset->addDatabase(cmd.argument()))
1543                                 buffer_.updateBibfilesCache();
1544                 }
1545                 break;
1546         }
1547
1548         case LFUN_BIBTEX_DATABASE_DEL: {
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->delDatabase(cmd.argument()))
1555                                 buffer_.updateBibfilesCache();
1556                 }
1557                 break;
1558         }
1559
1560         case LFUN_STATISTICS: {
1561                 DocIterator from, to;
1562                 if (cur.selection()) {
1563                         from = cur.selectionBegin();
1564                         to = cur.selectionEnd();
1565                 } else {
1566                         from = doc_iterator_begin(&buffer_);
1567                         to = doc_iterator_end(&buffer_);
1568                 }
1569                 int const words = countWords(from, to);
1570                 int const chars = countChars(from, to, false);
1571                 int const chars_blanks = countChars(from, to, true);
1572                 docstring message;
1573                 if (cur.selection())
1574                         message = _("Statistics for the selection:");
1575                 else
1576                         message = _("Statistics for the document:");
1577                 message += "\n\n";
1578                 if (words != 1)
1579                         message += bformat(_("%1$d words"), words);
1580                 else
1581                         message += _("One word");
1582                 message += "\n";
1583                 if (chars_blanks != 1)
1584                         message += bformat(_("%1$d characters (including blanks)"),
1585                                           chars_blanks);
1586                 else
1587                         message += _("One character (including blanks)");
1588                 message += "\n";
1589                 if (chars != 1)
1590                         message += bformat(_("%1$d characters (excluding blanks)"),
1591                                           chars);
1592                 else
1593                         message += _("One character (excluding blanks)");
1594
1595                 Alert::information(_("Statistics"), message);
1596         }
1597                 break;
1598
1599         case LFUN_BUFFER_TOGGLE_COMPRESSION:
1600                 // turn compression on/off
1601                 buffer_.params().compressed = !buffer_.params().compressed;
1602                 break;
1603
1604         case LFUN_LABEL_COPY_AS_REF: {
1605                 // if there is an inset at cursor, try to copy it
1606                 Inset * inset = &cur.inset();
1607                 if (!inset || !inset->asInsetMath())
1608                         inset = cur.nextInset();
1609                 if (inset) {
1610                         FuncRequest tmpcmd = cmd;
1611                         inset->dispatch(cur, tmpcmd);
1612                 }
1613                 if (!cur.result().dispatched())
1614                         // It did not work too; no action needed.
1615                         break;
1616                 cur.clearSelection();
1617                 dr.update(Update::SinglePar | Update::FitCursor);
1618                 break;
1619         }
1620
1621         case LFUN_SCREEN_UP:
1622         case LFUN_SCREEN_DOWN: {
1623                 Point p = getPos(cur, cur.boundary());
1624                 // This code has been commented out to enable to scroll down a
1625                 // document, even if there are large insets in it (see bug #5465).
1626                 /*if (p.y_ < 0 || p.y_ > height_) {
1627                         // The cursor is off-screen so recenter before proceeding.
1628                         showCursor();
1629                         p = getPos(cur, cur.boundary());
1630                 }*/
1631                 int const scrolled = scroll(cmd.action == LFUN_SCREEN_UP
1632                         ? -height_ : height_);
1633                 if (cmd.action == LFUN_SCREEN_UP && scrolled > -height_)
1634                         p = Point(0, 0);
1635                 if (cmd.action == LFUN_SCREEN_DOWN && scrolled < height_)
1636                         p = Point(width_, height_);
1637                 Cursor old = cur;
1638                 bool const in_texted = cur.inTexted();
1639                 cur.reset();
1640                 buffer_.changed(true);
1641                 d->text_metrics_[&buffer_.text()].editXY(cur, p.x_, p.y_,
1642                         true, cmd.action == LFUN_SCREEN_UP); 
1643                 //FIXME: what to do with cur.x_target()?
1644                 bool update = in_texted && cur.bv().checkDepm(cur, old);
1645                 cur.finishUndo();
1646                 if (update)
1647                         dr.update(Update::Force | Update::FitCursor);
1648                 break;
1649         }
1650
1651         case LFUN_SCROLL:
1652                 lfunScroll(cmd);
1653                 break;
1654
1655         case LFUN_SCREEN_UP_SELECT: {
1656                 cur.selHandle(true);
1657                 if (isTopScreen()) {
1658                         lyx::dispatch(FuncRequest(LFUN_BUFFER_BEGIN_SELECT));
1659                         cur.finishUndo();
1660                         break;
1661                 }
1662                 int y = getPos(cur, cur.boundary()).y_;
1663                 int const ymin = y - height_ + defaultRowHeight();
1664                 while (y > ymin && cur.up())
1665                         y = getPos(cur, cur.boundary()).y_;
1666
1667                 cur.finishUndo();
1668                 dr.update(Update::SinglePar | Update::FitCursor);
1669                 break;
1670         }
1671
1672         case LFUN_SCREEN_DOWN_SELECT: {
1673                 cur.selHandle(true);
1674                 if (isBottomScreen()) {
1675                         lyx::dispatch(FuncRequest(LFUN_BUFFER_END_SELECT));
1676                         cur.finishUndo();
1677                         break;
1678                 }
1679                 int y = getPos(cur, cur.boundary()).y_;
1680                 int const ymax = y + height_ - defaultRowHeight();
1681                 while (y < ymax && cur.down())
1682                         y = getPos(cur, cur.boundary()).y_;
1683
1684                 cur.finishUndo();
1685                 dr.update(Update::SinglePar | Update::FitCursor);
1686                 break;
1687         }
1688
1689
1690         // This would be in Buffer class if only Cursor did not
1691         // require a bufferview
1692         case LFUN_INSET_FORALL: {
1693                 docstring const name = from_utf8(cmd.getArg(0));
1694                 string const commandstr = cmd.getLongArg(1);
1695                 FuncRequest const fr = lyxaction.lookupFunc(commandstr);
1696
1697                 // an arbitrary number to limit number of iterations
1698                 const int max_iter = 10000;
1699                 int iterations = 0;
1700                 Cursor & cur = d->cursor_;
1701                 Cursor const savecur = cur;
1702                 cur.reset();
1703                 if (!cur.nextInset())
1704                         cur.forwardInset();
1705                 cur.beginUndoGroup();
1706                 while(cur && iterations < max_iter) {
1707                         Inset * ins = cur.nextInset();
1708                         if (!ins)
1709                                 break;
1710                         docstring insname = ins->name();
1711                         while (!insname.empty()) {
1712                                 if (insname == name || name == from_utf8("*")) {
1713                                         cur.recordUndo();
1714                                         lyx::dispatch(fr);
1715                                         ++iterations;
1716                                         break;
1717                                 }
1718                                 size_t const i = insname.rfind(':');
1719                                 if (i == string::npos)
1720                                         break;
1721                                 insname = insname.substr(0, i);
1722                         }
1723                         cur.forwardInset();
1724                 }
1725                 cur.endUndoGroup();
1726                 cur = savecur;
1727                 cur.fixIfBroken();
1728                 dr.update(Update::Force);
1729
1730                 if (iterations >= max_iter) {
1731                         dr.setError(true);
1732                         dr.setMessage(bformat(_("`inset-forall' interrupted because number of actions is larger than %1$d"), max_iter));
1733                 } else
1734                         dr.setMessage(bformat(_("Applied \"%1$s\" to %2$d insets"), from_utf8(commandstr), iterations));
1735                 break;
1736         }
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                 dr.update(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                 dr.update(Update::SinglePar | Update::FitCursor);
1847                 break;
1848         }
1849
1850         default:
1851                 dispatched = false;
1852                 break;
1853         }
1854
1855         buffer_.undo().endUndoGroup();
1856         dr.dispatched(dispatched);
1857         return;
1858 }
1859
1860
1861 docstring const BufferView::requestSelection()
1862 {
1863         Cursor & cur = d->cursor_;
1864
1865         LYXERR(Debug::SELECTION, "requestSelection: cur.selection: " << cur.selection());
1866         if (!cur.selection()) {
1867                 d->xsel_cache_.set = false;
1868                 return docstring();
1869         }
1870
1871         LYXERR(Debug::SELECTION, "requestSelection: xsel_cache.set: " << d->xsel_cache_.set);
1872         if (!d->xsel_cache_.set ||
1873             cur.top() != d->xsel_cache_.cursor ||
1874             cur.anchor_.top() != d->xsel_cache_.anchor)
1875         {
1876                 d->xsel_cache_.cursor = cur.top();
1877                 d->xsel_cache_.anchor = cur.anchor_.top();
1878                 d->xsel_cache_.set = cur.selection();
1879                 return cur.selectionAsString(false);
1880         }
1881         return docstring();
1882 }
1883
1884
1885 void BufferView::clearSelection()
1886 {
1887         d->cursor_.clearSelection();
1888         // Clear the selection buffer. Otherwise a subsequent
1889         // middle-mouse-button paste would use the selection buffer,
1890         // not the more current external selection.
1891         cap::clearSelection();
1892         d->xsel_cache_.set = false;
1893         // The buffer did not really change, but this causes the
1894         // redraw we need because we cleared the selection above.
1895         buffer_.changed(false);
1896 }
1897
1898
1899 void BufferView::resize(int width, int height)
1900 {
1901         // Update from work area
1902         width_ = width;
1903         height_ = height;
1904
1905         // Clear the paragraph height cache.
1906         d->par_height_.clear();
1907         // Redo the metrics.
1908         updateMetrics();
1909 }
1910
1911
1912 Inset const * BufferView::getCoveringInset(Text const & text,
1913                 int x, int y) const
1914 {
1915         TextMetrics & tm = d->text_metrics_[&text];
1916         Inset * inset = tm.checkInsetHit(x, y);
1917         if (!inset)
1918                 return 0;
1919
1920         if (!inset->descendable(*this))
1921                 // No need to go further down if the inset is not
1922                 // descendable.
1923                 return inset;
1924
1925         size_t cell_number = inset->nargs();
1926         // Check all the inner cell.
1927         for (size_t i = 0; i != cell_number; ++i) {
1928                 Text const * inner_text = inset->getText(i);
1929                 if (inner_text) {
1930                         // Try deeper.
1931                         Inset const * inset_deeper =
1932                                 getCoveringInset(*inner_text, x, y);
1933                         if (inset_deeper)
1934                                 return inset_deeper;
1935                 }
1936         }
1937
1938         return inset;
1939 }
1940
1941
1942 void BufferView::mouseEventDispatch(FuncRequest const & cmd0)
1943 {
1944         //lyxerr << "[ cmd0 " << cmd0 << "]" << endl;
1945
1946         // This is only called for mouse related events including
1947         // LFUN_FILE_OPEN generated by drag-and-drop.
1948         FuncRequest cmd = cmd0;
1949
1950         Cursor old = cursor();
1951         Cursor cur(*this);
1952         cur.push(buffer_.inset());
1953         cur.setSelection(d->cursor_.selection());
1954
1955         // Either the inset under the cursor or the
1956         // surrounding Text will handle this event.
1957
1958         // make sure we stay within the screen...
1959         cmd.y = min(max(cmd.y, -1), height_);
1960
1961         if (cmd.action == LFUN_MOUSE_MOTION && cmd.button() == mouse_button::none) {
1962
1963                 // Get inset under mouse, if there is one.
1964                 Inset const * covering_inset =
1965                         getCoveringInset(buffer_.text(), cmd.x, cmd.y);
1966                 if (covering_inset == d->last_inset_)
1967                         // Same inset, no need to do anything...
1968                         return;
1969
1970                 bool need_redraw = false;
1971                 // const_cast because of setMouseHover().
1972                 Inset * inset = const_cast<Inset *>(covering_inset);
1973                 if (d->last_inset_)
1974                         // Remove the hint on the last hovered inset (if any).
1975                         need_redraw |= d->last_inset_->setMouseHover(false);
1976                 if (inset)
1977                         // Highlighted the newly hovered inset (if any).
1978                         need_redraw |= inset->setMouseHover(true);
1979                 d->last_inset_ = inset;
1980                 if (!need_redraw)
1981                         return;
1982
1983                 LYXERR(Debug::PAINTING, "Mouse hover detected at: ("
1984                         << cmd.x << ", " << cmd.y << ")");
1985
1986                 d->update_strategy_ = DecorationUpdate;
1987
1988                 // This event (moving without mouse click) is not passed further.
1989                 // This should be changed if it is further utilized.
1990                 buffer_.changed(false);
1991                 return;
1992         }
1993
1994         // Build temporary cursor.
1995         Inset * inset = d->text_metrics_[&buffer_.text()].editXY(cur, cmd.x, cmd.y);
1996
1997         // Put anchor at the same position.
1998         cur.resetAnchor();
1999
2000         cur.beginUndoGroup();
2001
2002         // Try to dispatch to an non-editable inset near this position
2003         // via the temp cursor. If the inset wishes to change the real
2004         // cursor it has to do so explicitly by using
2005         //  cur.bv().cursor() = cur;  (or similar)
2006         if (inset)
2007                 inset->dispatch(cur, cmd);
2008
2009         // Now dispatch to the temporary cursor. If the real cursor should
2010         // be modified, the inset's dispatch has to do so explicitly.
2011         if (!inset || !cur.result().dispatched())
2012                 cur.dispatch(cmd);
2013
2014         cur.endUndoGroup();
2015
2016         // Notify left insets
2017         if (cur != old) {
2018                 old.fixIfBroken();
2019                 bool badcursor = notifyCursorLeavesOrEnters(old, cur);
2020                 if (badcursor)
2021                         cursor().fixIfBroken();
2022         }
2023         
2024         // Do we have a selection?
2025         theSelection().haveSelection(cursor().selection());
2026
2027         // If the command has been dispatched,
2028         if (cur.result().dispatched() || cur.result().update())
2029                 processUpdateFlags(cur.result().update());
2030 }
2031
2032
2033 void BufferView::lfunScroll(FuncRequest const & cmd)
2034 {
2035         string const scroll_type = cmd.getArg(0);
2036         int const scroll_step = 
2037                 (scroll_type == "line") ? d->scrollbarParameters_.single_step
2038                 : (scroll_type == "page") ? d->scrollbarParameters_.page_step : 0;
2039         if (scroll_step == 0)
2040                 return;
2041         string const scroll_quantity = cmd.getArg(1);
2042         if (scroll_quantity == "up")
2043                 scrollUp(scroll_step);
2044         else if (scroll_quantity == "down")
2045                 scrollDown(scroll_step);
2046         else {
2047                 int const scroll_value = convert<int>(scroll_quantity);
2048                 if (scroll_value)
2049                         scroll(scroll_step * scroll_value);
2050         }
2051         buffer_.changed(true);
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                                 lyx::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         buffer_.changed(true);
2238         return true;
2239 }
2240
2241
2242 bool BufferView::mouseSetCursor(Cursor & cur, bool select)
2243 {
2244         LASSERT(&cur.bv() == this, /**/);
2245
2246         if (!select)
2247                 // this event will clear selection so we save selection for
2248                 // persistent selection
2249                 cap::saveSelection(cursor());
2250
2251         d->cursor_.macroModeClose();
2252
2253         // Has the cursor just left the inset?
2254         bool leftinset = (&d->cursor_.inset() != &cur.inset());
2255         if (leftinset)
2256                 d->cursor_.fixIfBroken();
2257
2258         // FIXME: shift-mouse selection doesn't work well across insets.
2259         bool do_selection = select && &d->cursor_.anchor().inset() == &cur.inset();
2260
2261         // do the dEPM magic if needed
2262         // FIXME: (1) move this to InsetText::notifyCursorLeaves?
2263         // FIXME: (2) if we had a working InsetText::notifyCursorLeaves,
2264         // the leftinset bool would not be necessary (badcursor instead).
2265         bool update = leftinset;
2266         if (!do_selection && d->cursor_.inTexted())
2267                 update |= checkDepm(cur, d->cursor_);
2268
2269         if (!do_selection)
2270                 d->cursor_.resetAnchor();
2271         d->cursor_.setCursor(cur);
2272         d->cursor_.boundary(cur.boundary());
2273         if (do_selection)
2274                 d->cursor_.setSelection();
2275         else
2276                 d->cursor_.clearSelection();
2277
2278         d->cursor_.finishUndo();
2279         d->cursor_.setCurrentFont();
2280         return update;
2281 }
2282
2283
2284 void BufferView::putSelectionAt(DocIterator const & cur,
2285                                 int length, bool backwards)
2286 {
2287         d->cursor_.clearSelection();
2288
2289         setCursor(cur);
2290
2291         if (length) {
2292                 if (backwards) {
2293                         d->cursor_.pos() += length;
2294                         d->cursor_.setSelection(d->cursor_, -length);
2295                 } else
2296                         d->cursor_.setSelection(d->cursor_, length);
2297         }
2298         // Ensure a redraw happens in any case because the new selection could 
2299         // possibly be on the same screen as the previous selection.
2300         processUpdateFlags(Update::Force | Update::FitCursor);
2301 }
2302
2303
2304 Cursor & BufferView::cursor()
2305 {
2306         return d->cursor_;
2307 }
2308
2309
2310 Cursor const & BufferView::cursor() const
2311 {
2312         return d->cursor_;
2313 }
2314
2315
2316 pit_type BufferView::anchor_ref() const
2317 {
2318         return d->anchor_pit_;
2319 }
2320
2321
2322 bool BufferView::singleParUpdate()
2323 {
2324         Text & buftext = buffer_.text();
2325         pit_type const bottom_pit = d->cursor_.bottom().pit();
2326         TextMetrics & tm = textMetrics(&buftext);
2327         int old_height = tm.parMetrics(bottom_pit).height();
2328
2329         // make sure inline completion pointer is ok
2330         if (d->inlineCompletionPos_.fixIfBroken())
2331                 d->inlineCompletionPos_ = DocIterator();
2332
2333         // In Single Paragraph mode, rebreak only
2334         // the (main text, not inset!) paragraph containing the cursor.
2335         // (if this paragraph contains insets etc., rebreaking will
2336         // recursively descend)
2337         tm.redoParagraph(bottom_pit);
2338         ParagraphMetrics const & pm = tm.parMetrics(bottom_pit);                
2339         if (pm.height() != old_height)
2340                 // Paragraph height has changed so we cannot proceed to
2341                 // the singlePar optimisation.
2342                 return false;
2343
2344         d->update_strategy_ = SingleParUpdate;
2345
2346         LYXERR(Debug::PAINTING, "\ny1: " << pm.position() - pm.ascent()
2347                 << " y2: " << pm.position() + pm.descent()
2348                 << " pit: " << bottom_pit
2349                 << " singlepar: 1");
2350         return true;
2351 }
2352
2353
2354 void BufferView::updateMetrics()
2355 {
2356         if (height_ == 0 || width_ == 0)
2357                 return;
2358
2359         Text & buftext = buffer_.text();
2360         pit_type const npit = int(buftext.paragraphs().size());
2361
2362         // Clear out the position cache in case of full screen redraw,
2363         d->coord_cache_.clear();
2364
2365         // Clear out paragraph metrics to avoid having invalid metrics
2366         // in the cache from paragraphs not relayouted below
2367         // The complete text metrics will be redone.
2368         d->text_metrics_.clear();
2369
2370         TextMetrics & tm = textMetrics(&buftext);
2371
2372         // make sure inline completion pointer is ok
2373         if (d->inlineCompletionPos_.fixIfBroken())
2374                 d->inlineCompletionPos_ = DocIterator();
2375         
2376         if (d->anchor_pit_ >= npit)
2377                 // The anchor pit must have been deleted...
2378                 d->anchor_pit_ = npit - 1;
2379
2380         // Rebreak anchor paragraph.
2381         tm.redoParagraph(d->anchor_pit_);
2382         ParagraphMetrics & anchor_pm = tm.par_metrics_[d->anchor_pit_];
2383         
2384         // position anchor
2385         if (d->anchor_pit_ == 0) {
2386                 int scrollRange = d->scrollbarParameters_.max - d->scrollbarParameters_.min;
2387                 
2388                 // Complete buffer visible? Then it's easy.
2389                 if (scrollRange == 0)
2390                         d->anchor_ypos_ = anchor_pm.ascent();
2391         
2392                 // FIXME: Some clever handling needed to show
2393                 // the _first_ paragraph up to the top if the cursor is
2394                 // in the first line.
2395         }               
2396         anchor_pm.setPosition(d->anchor_ypos_);
2397
2398         LYXERR(Debug::PAINTING, "metrics: "
2399                 << " anchor pit = " << d->anchor_pit_
2400                 << " anchor ypos = " << d->anchor_ypos_);
2401
2402         // Redo paragraphs above anchor if necessary.
2403         int y1 = d->anchor_ypos_ - anchor_pm.ascent();
2404         // We are now just above the anchor paragraph.
2405         pit_type pit1 = d->anchor_pit_ - 1;
2406         for (; pit1 >= 0 && y1 >= 0; --pit1) {
2407                 tm.redoParagraph(pit1);
2408                 ParagraphMetrics & pm = tm.par_metrics_[pit1];
2409                 y1 -= pm.descent();
2410                 // Save the paragraph position in the cache.
2411                 pm.setPosition(y1);
2412                 y1 -= pm.ascent();
2413         }
2414
2415         // Redo paragraphs below the anchor if necessary.
2416         int y2 = d->anchor_ypos_ + anchor_pm.descent();
2417         // We are now just below the anchor paragraph.
2418         pit_type pit2 = d->anchor_pit_ + 1;
2419         for (; pit2 < npit && y2 <= height_; ++pit2) {
2420                 tm.redoParagraph(pit2);
2421                 ParagraphMetrics & pm = tm.par_metrics_[pit2];
2422                 y2 += pm.ascent();
2423                 // Save the paragraph position in the cache.
2424                 pm.setPosition(y2);
2425                 y2 += pm.descent();
2426         }
2427
2428         LYXERR(Debug::PAINTING, "Metrics: "
2429                 << " anchor pit = " << d->anchor_pit_
2430                 << " anchor ypos = " << d->anchor_ypos_
2431                 << " y1 = " << y1
2432                 << " y2 = " << y2
2433                 << " pit1 = " << pit1
2434                 << " pit2 = " << pit2);
2435
2436         d->update_strategy_ = FullScreenUpdate;
2437
2438         if (lyxerr.debugging(Debug::WORKAREA)) {
2439                 LYXERR(Debug::WORKAREA, "BufferView::updateMetrics");
2440                 d->coord_cache_.dump();
2441         }
2442 }
2443
2444
2445 void BufferView::insertLyXFile(FileName const & fname)
2446 {
2447         LASSERT(d->cursor_.inTexted(), /**/);
2448
2449         // Get absolute path of file and add ".lyx"
2450         // to the filename if necessary
2451         FileName filename = fileSearch(string(), fname.absFilename(), "lyx");
2452
2453         docstring const disp_fn = makeDisplayPath(filename.absFilename());
2454         // emit message signal.
2455         message(bformat(_("Inserting document %1$s..."), disp_fn));
2456
2457         docstring res;
2458         Buffer buf("", false);
2459         if (buf.loadLyXFile(filename)) {
2460                 ErrorList & el = buffer_.errorList("Parse");
2461                 // Copy the inserted document error list into the current buffer one.
2462                 el = buf.errorList("Parse");
2463                 buffer_.undo().recordUndo(d->cursor_);
2464                 cap::pasteParagraphList(d->cursor_, buf.paragraphs(),
2465                                              buf.params().documentClassPtr(), el);
2466                 res = _("Document %1$s inserted.");
2467         } else {
2468                 res = _("Could not insert document %1$s");
2469         }
2470
2471         buffer_.changed(true);
2472         // emit message signal.
2473         message(bformat(res, disp_fn));
2474         buffer_.errors("Parse");
2475 }
2476
2477
2478 Point BufferView::coordOffset(DocIterator const & dit, bool boundary) const
2479 {
2480         int x = 0;
2481         int y = 0;
2482         int lastw = 0;
2483
2484         // Addup contribution of nested insets, from inside to outside,
2485         // keeping the outer paragraph for a special handling below
2486         for (size_t i = dit.depth() - 1; i >= 1; --i) {
2487                 CursorSlice const & sl = dit[i];
2488                 int xx = 0;
2489                 int yy = 0;
2490                 
2491                 // get relative position inside sl.inset()
2492                 sl.inset().cursorPos(*this, sl, boundary && (i + 1 == dit.depth()), xx, yy);
2493                 
2494                 // Make relative position inside of the edited inset relative to sl.inset()
2495                 x += xx;
2496                 y += yy;
2497                 
2498                 // In case of an RTL inset, the edited inset will be positioned to the left
2499                 // of xx:yy
2500                 if (sl.text()) {
2501                         bool boundary_i = boundary && i + 1 == dit.depth();
2502                         bool rtl = textMetrics(sl.text()).isRTL(sl, boundary_i);
2503                         if (rtl)
2504                                 x -= lastw;
2505                 }
2506
2507                 // remember width for the case that sl.inset() is positioned in an RTL inset
2508                 if (i && dit[i - 1].text()) {
2509                         // If this Inset is inside a Text Inset, retrieve the Dimension
2510                         // from the containing text instead of using Inset::dimension() which
2511                         // might not be implemented.
2512                         // FIXME (Abdel 23/09/2007): this is a bit messy because of the
2513                         // elimination of Inset::dim_ cache. This coordOffset() method needs
2514                         // to be rewritten in light of the new design.
2515                         Dimension const & dim = parMetrics(dit[i - 1].text(),
2516                                 dit[i - 1].pit()).insetDimension(&sl.inset());
2517                         lastw = dim.wid;
2518                 } else {
2519                         Dimension const dim = sl.inset().dimension(*this);
2520                         lastw = dim.wid;
2521                 }
2522                 
2523                 //lyxerr << "Cursor::getPos, i: "
2524                 // << i << " x: " << xx << " y: " << y << endl;
2525         }
2526
2527         // Add contribution of initial rows of outermost paragraph
2528         CursorSlice const & sl = dit[0];
2529         TextMetrics const & tm = textMetrics(sl.text());
2530         ParagraphMetrics const & pm = tm.parMetrics(sl.pit());
2531         LASSERT(!pm.rows().empty(), /**/);
2532         y -= pm.rows()[0].ascent();
2533 #if 1
2534         // FIXME: document this mess
2535         size_t rend;
2536         if (sl.pos() > 0 && dit.depth() == 1) {
2537                 int pos = sl.pos();
2538                 if (pos && boundary)
2539                         --pos;
2540 //              lyxerr << "coordOffset: boundary:" << boundary << " depth:" << dit.depth() << " pos:" << pos << " sl.pos:" << sl.pos() << endl;
2541                 rend = pm.pos2row(pos);
2542         } else
2543                 rend = pm.pos2row(sl.pos());
2544 #else
2545         size_t rend = pm.pos2row(sl.pos());
2546 #endif
2547         for (size_t rit = 0; rit != rend; ++rit)
2548                 y += pm.rows()[rit].height();
2549         y += pm.rows()[rend].ascent();
2550         
2551         TextMetrics const & bottom_tm = textMetrics(dit.bottom().text());
2552         
2553         // Make relative position from the nested inset now bufferview absolute.
2554         int xx = bottom_tm.cursorX(dit.bottom(), boundary && dit.depth() == 1);
2555         x += xx;
2556         
2557         // In the RTL case place the nested inset at the left of the cursor in 
2558         // the outer paragraph
2559         bool boundary_1 = boundary && 1 == dit.depth();
2560         bool rtl = bottom_tm.isRTL(dit.bottom(), boundary_1);
2561         if (rtl)
2562                 x -= lastw;
2563         
2564         return Point(x, y);
2565 }
2566
2567
2568 Point BufferView::getPos(DocIterator const & dit, bool boundary) const
2569 {
2570         if (!paragraphVisible(dit))
2571                 return Point(-1, -1);
2572
2573         CursorSlice const & bot = dit.bottom();
2574         TextMetrics const & tm = textMetrics(bot.text());
2575
2576         Point p = coordOffset(dit, boundary); // offset from outer paragraph
2577         p.y_ += tm.parMetrics(bot.pit()).position();
2578         return p;
2579 }
2580
2581
2582 bool BufferView::paragraphVisible(DocIterator const & dit) const
2583 {
2584         CursorSlice const & bot = dit.bottom();
2585         TextMetrics const & tm = textMetrics(bot.text());
2586
2587         return tm.contains(bot.pit());
2588 }
2589
2590
2591 void BufferView::cursorPosAndHeight(Point & p, int & h) const
2592 {
2593         Cursor const & cur = cursor();
2594         Font const font = cur.getFont();
2595         frontend::FontMetrics const & fm = theFontMetrics(font);
2596         int const asc = fm.maxAscent();
2597         int const des = fm.maxDescent();
2598         h = asc + des;
2599         p = getPos(cur, cur.boundary());
2600         p.y_ -= asc;
2601 }
2602
2603
2604 bool BufferView::cursorInView(Point const & p, int h) const
2605 {
2606         Cursor const & cur = cursor();
2607         // does the cursor touch the screen ?
2608         if (p.y_ + h < 0 || p.y_ >= workHeight() || !paragraphVisible(cur))
2609                 return false;
2610         return true;
2611 }
2612
2613
2614 void BufferView::draw(frontend::Painter & pain)
2615 {
2616         if (height_ == 0 || width_ == 0)
2617                 return;
2618         LYXERR(Debug::PAINTING, "\t\t*** START DRAWING ***");
2619
2620         Text & text = buffer_.text();
2621         TextMetrics const & tm = d->text_metrics_[&text];
2622         int const y = tm.first().second->position();
2623         PainterInfo pi(this, pain);
2624
2625         switch (d->update_strategy_) {
2626
2627         case NoScreenUpdate:
2628                 // If no screen painting is actually needed, only some the different
2629                 // coordinates of insets and paragraphs needs to be updated.
2630                 pi.full_repaint = true;
2631                 pi.pain.setDrawingEnabled(false);
2632                 tm.draw(pi, 0, y);
2633                 break;
2634
2635         case SingleParUpdate:
2636                 pi.full_repaint = false;
2637                 // In general, only the current row of the outermost paragraph
2638                 // will be redrawn. Particular cases where selection spans
2639                 // multiple paragraph are correctly detected in TextMetrics.
2640                 tm.draw(pi, 0, y);
2641                 break;
2642
2643         case DecorationUpdate:
2644                 // FIXME: We should also distinguish DecorationUpdate to avoid text
2645                 // drawing if possible. This is not possible to do easily right now
2646                 // because of the single backing pixmap.
2647
2648         case FullScreenUpdate:
2649                 // The whole screen, including insets, will be refreshed.
2650                 pi.full_repaint = true;
2651
2652                 // Clear background.
2653                 pain.fillRectangle(0, 0, width_, height_,
2654                         pi.backgroundColor(&buffer_.inset()));
2655
2656                 // Draw everything.
2657                 tm.draw(pi, 0, y);
2658
2659                 // and possibly grey out below
2660                 pair<pit_type, ParagraphMetrics const *> lastpm = tm.last();
2661                 int const y2 = lastpm.second->position() + lastpm.second->descent();
2662                 
2663                 if (y2 < height_) {
2664                         Color color = buffer().isInternal() 
2665                                 ? Color_background : Color_bottomarea;
2666                         pain.fillRectangle(0, y2, width_, height_ - y2, color);
2667                 }
2668                 break;
2669         }
2670         LYXERR(Debug::PAINTING, "\n\t\t*** END DRAWING  ***");
2671
2672         // The scrollbar needs an update.
2673         updateScrollbar();
2674
2675         // Normalize anchor for next time
2676         pair<pit_type, ParagraphMetrics const *> firstpm = tm.first();
2677         pair<pit_type, ParagraphMetrics const *> lastpm = tm.last();
2678         for (pit_type pit = firstpm.first; pit <= lastpm.first; ++pit) {
2679                 ParagraphMetrics const & pm = tm.parMetrics(pit);
2680                 if (pm.position() + pm.descent() > 0) {
2681                         d->anchor_pit_ = pit;
2682                         d->anchor_ypos_ = pm.position();
2683                         break;
2684                 }
2685         }
2686         LYXERR(Debug::PAINTING, "Found new anchor pit = " << d->anchor_pit_
2687                 << "  anchor ypos = " << d->anchor_ypos_);
2688 }
2689
2690
2691 void BufferView::message(docstring const & msg)
2692 {
2693         if (d->gui_)
2694                 d->gui_->message(msg);
2695 }
2696
2697
2698 void BufferView::showDialog(string const & name)
2699 {
2700         if (d->gui_)
2701                 d->gui_->showDialog(name, string());
2702 }
2703
2704
2705 void BufferView::showDialog(string const & name,
2706         string const & data, Inset * inset)
2707 {
2708         if (d->gui_)
2709                 d->gui_->showDialog(name, data, inset);
2710 }
2711
2712
2713 void BufferView::updateDialog(string const & name, string const & data)
2714 {
2715         if (d->gui_)
2716                 d->gui_->updateDialog(name, data);
2717 }
2718
2719
2720 void BufferView::setGuiDelegate(frontend::GuiBufferViewDelegate * gui)
2721 {
2722         d->gui_ = gui;
2723 }
2724
2725
2726 // FIXME: Move this out of BufferView again
2727 docstring BufferView::contentsOfPlaintextFile(FileName const & fname)
2728 {
2729         if (!fname.isReadableFile()) {
2730                 docstring const error = from_ascii(strerror(errno));
2731                 docstring const file = makeDisplayPath(fname.absFilename(), 50);
2732                 docstring const text =
2733                   bformat(_("Could not read the specified document\n"
2734                             "%1$s\ndue to the error: %2$s"), file, error);
2735                 Alert::error(_("Could not read file"), text);
2736                 return docstring();
2737         }
2738
2739         if (!fname.isReadableFile()) {
2740                 docstring const file = makeDisplayPath(fname.absFilename(), 50);
2741                 docstring const text =
2742                   bformat(_("%1$s\n is not readable."), file);
2743                 Alert::error(_("Could not open file"), text);
2744                 return docstring();
2745         }
2746
2747         // FIXME UNICODE: We don't know the encoding of the file
2748         docstring file_content = fname.fileContents("UTF-8");
2749         if (file_content.empty()) {
2750                 Alert::error(_("Reading not UTF-8 encoded file"),
2751                              _("The file is not UTF-8 encoded.\n"
2752                                "It will be read as local 8Bit-encoded.\n"
2753                                "If this does not give the correct result\n"
2754                                "then please change the encoding of the file\n"
2755                                "to UTF-8 with a program other than LyX.\n"));
2756                 file_content = fname.fileContents("local8bit");
2757         }
2758
2759         return normalize_c(file_content);
2760 }
2761
2762
2763 void BufferView::insertPlaintextFile(FileName const & f, bool asParagraph)
2764 {
2765         docstring const tmpstr = contentsOfPlaintextFile(f);
2766
2767         if (tmpstr.empty())
2768                 return;
2769
2770         Cursor & cur = cursor();
2771         cap::replaceSelection(cur);
2772         buffer_.undo().recordUndo(cur);
2773         if (asParagraph)
2774                 cur.innerText()->insertStringAsParagraphs(cur, tmpstr, cur.current_font);
2775         else
2776                 cur.innerText()->insertStringAsLines(cur, tmpstr, cur.current_font);
2777
2778         buffer_.changed(true);
2779 }
2780
2781
2782 docstring const & BufferView::inlineCompletion() const
2783 {
2784         return d->inlineCompletion_;
2785 }
2786
2787
2788 size_t const & BufferView::inlineCompletionUniqueChars() const
2789 {
2790         return d->inlineCompletionUniqueChars_;
2791 }
2792
2793
2794 DocIterator const & BufferView::inlineCompletionPos() const
2795 {
2796         return d->inlineCompletionPos_;
2797 }
2798
2799
2800 bool samePar(DocIterator const & a, DocIterator const & b)
2801 {
2802         if (a.empty() && b.empty())
2803                 return true;
2804         if (a.empty() || b.empty())
2805                 return false;
2806         if (a.depth() != b.depth())
2807                 return false;
2808         return &a.innerParagraph() == &b.innerParagraph();
2809 }
2810
2811
2812 void BufferView::setInlineCompletion(Cursor & cur, DocIterator const & pos, 
2813         docstring const & completion, size_t uniqueChars)
2814 {
2815         uniqueChars = min(completion.size(), uniqueChars);
2816         bool changed = d->inlineCompletion_ != completion
2817                 || d->inlineCompletionUniqueChars_ != uniqueChars;
2818         bool singlePar = true;
2819         d->inlineCompletion_ = completion;
2820         d->inlineCompletionUniqueChars_ = min(completion.size(), uniqueChars);
2821         
2822         //lyxerr << "setInlineCompletion pos=" << pos << " completion=" << completion << " uniqueChars=" << uniqueChars << std::endl;
2823         
2824         // at new position?
2825         DocIterator const & old = d->inlineCompletionPos_;
2826         if (old != pos) {
2827                 //lyxerr << "inlineCompletionPos changed" << std::endl;
2828                 // old or pos are in another paragraph?
2829                 if ((!samePar(cur, pos) && !pos.empty())
2830                     || (!samePar(cur, old) && !old.empty())) {
2831                         singlePar = false;
2832                         //lyxerr << "different paragraph" << std::endl;
2833                 }
2834                 d->inlineCompletionPos_ = pos;
2835         }
2836         
2837         // set update flags
2838         if (changed) {
2839                 if (singlePar && !(cur.disp_.update() & Update::Force))
2840                         cur.updateFlags(cur.disp_.update() | Update::SinglePar);
2841                 else
2842                         cur.updateFlags(cur.disp_.update() | Update::Force);
2843         }
2844 }
2845
2846 } // namespace lyx