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