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