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