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