]> git.lyx.org Git - features.git/blob - src/BufferView.cpp
move LFUN_BUFFER_PARAMS_APPLY to BufferView. I needed to make LyXFunc::updateLayout...
[features.git] / src / BufferView.cpp
1 /**
2  * \file BufferView.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Alfredo Braunstein
7  * \author Lars Gullik Bjønnes
8  * \author John Levon
9  * \author André Pönitz
10  * \author Jürgen Vigna
11  *
12  * Full author contact details are available in file CREDITS.
13  */
14
15 #include <config.h>
16
17 #include "BufferView.h"
18
19 #include "BranchList.h"
20 #include "Buffer.h"
21 #include "buffer_funcs.h"
22 #include "BufferList.h"
23 #include "BufferParams.h"
24 #include "CoordCache.h"
25 #include "Cursor.h"
26 #include "CutAndPaste.h"
27 #include "DispatchResult.h"
28 #include "ErrorList.h"
29 #include "factory.h"
30 #include "FloatList.h"
31 #include "FuncRequest.h"
32 #include "FuncStatus.h"
33 #include "Intl.h"
34 #include "InsetIterator.h"
35 #include "Language.h"
36 #include "LaTeXFeatures.h"
37 #include "Lexer.h"
38 #include "LyX.h"
39 #include "lyxfind.h"
40 #include "LyXFunc.h"
41 #include "Layout.h"
42 #include "LyXRC.h"
43 #include "MetricsInfo.h"
44 #include "Paragraph.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()) {
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         case LFUN_BUFFER_PARAMS_APPLY:
904                 flag.setEnabled(!buffer_.isReadonly());
905                 break;
906
907         case LFUN_UNDO:
908                 flag.setEnabled(buffer_.undo().hasUndoStack());
909                 break;
910         case LFUN_REDO:
911                 flag.setEnabled(buffer_.undo().hasRedoStack());
912                 break;
913         case LFUN_FILE_INSERT:
914         case LFUN_FILE_INSERT_PLAINTEXT_PARA:
915         case LFUN_FILE_INSERT_PLAINTEXT:
916         case LFUN_BOOKMARK_SAVE:
917                 // FIXME: Actually, these LFUNS should be moved to Text
918                 flag.setEnabled(cur.inTexted());
919                 break;
920
921         case LFUN_FONT_STATE:
922         case LFUN_LABEL_INSERT:
923         case LFUN_INFO_INSERT:
924         case LFUN_INSET_EDIT:
925         case LFUN_PARAGRAPH_GOTO:
926         case LFUN_NOTE_NEXT:
927         case LFUN_REFERENCE_NEXT:
928         case LFUN_WORD_FIND:
929         case LFUN_WORD_FIND_FORWARD:
930         case LFUN_WORD_FIND_BACKWARD:
931         case LFUN_WORD_FINDADV:
932         case LFUN_WORD_REPLACE:
933         case LFUN_MARK_OFF:
934         case LFUN_MARK_ON:
935         case LFUN_MARK_TOGGLE:
936         case LFUN_SCREEN_RECENTER:
937         case LFUN_SCREEN_SHOW_CURSOR:
938         case LFUN_BIBTEX_DATABASE_ADD:
939         case LFUN_BIBTEX_DATABASE_DEL:
940         case LFUN_NOTES_MUTATE:
941         case LFUN_ALL_INSETS_TOGGLE:
942         case LFUN_STATISTICS:
943         case LFUN_BRANCH_ADD_INSERT:
944         case LFUN_KEYMAP_OFF:
945         case LFUN_KEYMAP_PRIMARY:
946         case LFUN_KEYMAP_SECONDARY:
947         case LFUN_KEYMAP_TOGGLE:
948                 flag.setEnabled(true);
949                 break;
950
951         case LFUN_REGEXP_MODE:
952                 // FIXME: Test if current WorkArea is the search WorkArea
953                 flag.setEnabled(buffer().isInternal() && !cur.inRegexped());
954                 break;
955
956         case LFUN_LABEL_COPY_AS_REF: {
957                 // if there is an inset at cursor, see whether it
958                 // handles the lfun
959                 Inset * inset = cur.nextInset();
960                 if (!inset || !inset->getStatus(cur, cmd, flag))
961                         flag.setEnabled(false);
962                 break;
963         }
964
965         case LFUN_NEXT_INSET_MODIFY: {
966                 // this is the real function we want to invoke
967                 FuncRequest tmpcmd = cmd;
968                 tmpcmd.action = LFUN_INSET_MODIFY;
969                 // if there is an inset at cursor, see whether it
970                 // handles the lfun, other start from scratch
971                 Inset * inset = cur.nextInset();
972                 if (!inset || !inset->getStatus(cur, tmpcmd, flag))
973                         flag = lyx::getStatus(tmpcmd);
974                 break;
975         }
976
977         case LFUN_LABEL_GOTO: {
978                 flag.setEnabled(!cmd.argument().empty()
979                     || getInsetByCode<InsetRef>(cur, REF_CODE));
980                 break;
981         }
982
983         case LFUN_CHANGES_TRACK:
984                 flag.setEnabled(true);
985                 flag.setOnOff(buffer_.params().trackChanges);
986                 break;
987
988         case LFUN_CHANGES_OUTPUT:
989                 flag.setEnabled(true);
990                 flag.setOnOff(buffer_.params().outputChanges);
991                 break;
992
993         case LFUN_CHANGES_MERGE:
994         case LFUN_CHANGE_NEXT:
995         case LFUN_CHANGE_PREVIOUS:
996         case LFUN_ALL_CHANGES_ACCEPT:
997         case LFUN_ALL_CHANGES_REJECT:
998                 // TODO: context-sensitive enabling of LFUNs
999                 // In principle, these command should only be enabled if there
1000                 // is a change in the document. However, without proper
1001                 // optimizations, this will inevitably result in poor performance.
1002                 flag.setEnabled(true);
1003                 break;
1004
1005         case LFUN_BUFFER_TOGGLE_COMPRESSION: {
1006                 flag.setOnOff(buffer_.params().compressed);
1007                 break;
1008         }
1009         
1010         case LFUN_SCREEN_UP:
1011         case LFUN_SCREEN_DOWN:
1012         case LFUN_SCROLL:
1013         case LFUN_SCREEN_UP_SELECT:
1014         case LFUN_SCREEN_DOWN_SELECT:
1015                 flag.setEnabled(true);
1016                 break;
1017
1018         case LFUN_LAYOUT_TABULAR:
1019                 flag.setEnabled(cur.innerInsetOfType(TABULAR_CODE));
1020                 break;
1021
1022         case LFUN_LAYOUT:
1023                 flag.setEnabled(!cur.inset().forcePlainLayout(cur.idx()));
1024                 break;
1025
1026         case LFUN_LAYOUT_PARAGRAPH:
1027                 flag.setEnabled(cur.inset().allowParagraphCustomization(cur.idx()));
1028                 break;
1029
1030         case LFUN_DIALOG_SHOW_NEW_INSET:
1031                 // FIXME: this is wrong, but I do not understand the
1032                 // intent (JMarc)
1033                 if (cur.inset().lyxCode() == CAPTION_CODE)
1034                         return cur.inset().getStatus(cur, cmd, flag);
1035                 // FIXME we should consider passthru paragraphs too.
1036                 flag.setEnabled(!cur.inset().getLayout().isPassThru());
1037                 break;
1038
1039         default:
1040                 flag.setEnabled(false);
1041                 return false;
1042         }
1043
1044         return true;
1045 }
1046
1047
1048 bool BufferView::dispatch(FuncRequest const & cmd)
1049 {
1050         //lyxerr << [ cmd = " << cmd << "]" << endl;
1051
1052         // Make sure that the cached BufferView is correct.
1053         LYXERR(Debug::ACTION, " action[" << cmd.action << ']'
1054                 << " arg[" << to_utf8(cmd.argument()) << ']'
1055                 << " x[" << cmd.x << ']'
1056                 << " y[" << cmd.y << ']'
1057                 << " button[" << cmd.button() << ']');
1058
1059         Cursor & cur = d->cursor_;
1060
1061         switch (cmd.action) {
1062
1063         case LFUN_BUFFER_PARAMS_APPLY: {
1064                 DocumentClass const * const oldClass = buffer_.params().documentClassPtr();
1065                 cur.recordUndoFullDocument();
1066                 istringstream ss(to_utf8(cmd.argument()));
1067                 Lexer lex;
1068                 lex.setStream(ss);
1069                 int const unknown_tokens = buffer_.readHeader(lex);
1070                 if (unknown_tokens != 0) {
1071                         LYXERR0("Warning in LFUN_BUFFER_PARAMS_APPLY!\n"
1072                                                 << unknown_tokens << " unknown token"
1073                                                 << (unknown_tokens == 1 ? "" : "s"));
1074                 }
1075                 theLyXFunc().updateLayout(oldClass, &buffer_);
1076                         
1077                 // We are most certainly here because of a change in the document
1078                 // It is then better to make sure that all dialogs are in sync with
1079                 // current document settings.
1080                 processUpdateFlags(Update::Force | Update::FitCursor);
1081                 break;
1082         }
1083                 
1084         case LFUN_UNDO:
1085                 cur.message(_("Undo"));
1086                 cur.clearSelection();
1087                 if (!cur.textUndo())
1088                         cur.message(_("No further undo information"));
1089                 else
1090                         processUpdateFlags(Update::Force | Update::FitCursor);
1091                 break;
1092
1093         case LFUN_REDO:
1094                 cur.message(_("Redo"));
1095                 cur.clearSelection();
1096                 if (!cur.textRedo())
1097                         cur.message(_("No further redo information"));
1098                 else
1099                         processUpdateFlags(Update::Force | Update::FitCursor);
1100                 break;
1101
1102         case LFUN_FONT_STATE:
1103                 cur.message(cur.currentState());
1104                 break;
1105
1106         case LFUN_BOOKMARK_SAVE:
1107                 saveBookmark(convert<unsigned int>(to_utf8(cmd.argument())));
1108                 break;
1109
1110         case LFUN_LABEL_GOTO: {
1111                 docstring label = cmd.argument();
1112                 if (label.empty()) {
1113                         InsetRef * inset =
1114                                 getInsetByCode<InsetRef>(cur, REF_CODE);
1115                         if (inset) {
1116                                 label = inset->getParam("reference");
1117                                 // persistent=false: use temp_bookmark
1118                                 saveBookmark(0);
1119                         }
1120                 }
1121                 if (!label.empty())
1122                         gotoLabel(label);
1123                 break;
1124         }
1125         
1126         case LFUN_INSET_EDIT: {
1127                 FuncRequest fr(cmd);
1128                 // if there is an inset at cursor, see whether it
1129                 // can be modified.
1130                 Inset * inset = cur.nextInset();
1131                 if (inset)
1132                         inset->dispatch(cur, fr);
1133                 // if it did not work, try the underlying inset.
1134                 if (!inset || !cur.result().dispatched())
1135                         cur.dispatch(cmd);
1136
1137                 // FIXME I'm adding the last break to solve a crash,
1138                 // but that is obviously not right.
1139                 if (!cur.result().dispatched())
1140                         // It did not work too; no action needed.
1141                         break;
1142                 break;
1143         }
1144
1145         case LFUN_PARAGRAPH_GOTO: {
1146                 int const id = convert<int>(cmd.getArg(0));
1147                 int const pos = convert<int>(cmd.getArg(1));
1148                 int i = 0;
1149                 for (Buffer * b = &buffer_; i == 0 || b != &buffer_;
1150                         b = theBufferList().next(b)) {
1151
1152                         DocIterator dit = b->getParFromID(id);
1153                         if (dit.atEnd()) {
1154                                 LYXERR(Debug::INFO, "No matching paragraph found! [" << id << "].");
1155                                 ++i;
1156                                 continue;
1157                         }
1158                         LYXERR(Debug::INFO, "Paragraph " << dit.paragraph().id()
1159                                 << " found in buffer `"
1160                                 << b->absFileName() << "'.");
1161
1162                         if (b == &buffer_) {
1163                                 // Set the cursor
1164                                 dit.pos() = pos;
1165                                 setCursor(dit);
1166                                 processUpdateFlags(Update::Force | Update::FitCursor);
1167                         } else {
1168                                 // Switch to other buffer view and resend cmd
1169                                 theLyXFunc().dispatch(FuncRequest(
1170                                         LFUN_BUFFER_SWITCH, b->absFileName()));
1171                                 theLyXFunc().dispatch(cmd);
1172                         }
1173                         break;
1174                 }
1175                 break;
1176         }
1177
1178         case LFUN_NOTE_NEXT:
1179                 gotoInset(this, NOTE_CODE, false);
1180                 break;
1181
1182         case LFUN_REFERENCE_NEXT: {
1183                 vector<InsetCode> tmp;
1184                 tmp.push_back(LABEL_CODE);
1185                 tmp.push_back(REF_CODE);
1186                 gotoInset(this, tmp, true);
1187                 break;
1188         }
1189
1190         case LFUN_CHANGES_TRACK:
1191                 buffer_.params().trackChanges = !buffer_.params().trackChanges;
1192                 break;
1193
1194         case LFUN_CHANGES_OUTPUT:
1195                 buffer_.params().outputChanges = !buffer_.params().outputChanges;
1196                 if (buffer_.params().outputChanges) {
1197                         bool dvipost    = LaTeXFeatures::isAvailable("dvipost");
1198                         bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
1199                                           LaTeXFeatures::isAvailable("xcolor");
1200
1201                         if (!dvipost && !xcolorulem) {
1202                                 Alert::warning(_("Changes not shown in LaTeX output"),
1203                                                _("Changes will not be highlighted in LaTeX output, "
1204                                                  "because neither dvipost nor xcolor/ulem are installed.\n"
1205                                                  "Please install these packages or redefine "
1206                                                  "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
1207                         } else if (!xcolorulem) {
1208                                 Alert::warning(_("Changes not shown in LaTeX output"),
1209                                                _("Changes will not be highlighted in LaTeX output "
1210                                                  "when using pdflatex, because xcolor and ulem are not installed.\n"
1211                                                  "Please install both packages or redefine "
1212                                                  "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
1213                         }
1214                 }
1215                 break;
1216
1217         case LFUN_CHANGE_NEXT:
1218                 findNextChange(this);
1219                 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1220                 processUpdateFlags(Update::Force | Update::FitCursor);
1221                 break;
1222         
1223         case LFUN_CHANGE_PREVIOUS:
1224                 findPreviousChange(this);
1225                 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1226                 processUpdateFlags(Update::Force | Update::FitCursor);
1227                 break;
1228
1229         case LFUN_CHANGES_MERGE:
1230                 if (findNextChange(this) || findPreviousChange(this)) {
1231                         processUpdateFlags(Update::Force | Update::FitCursor);
1232                         showDialog("changes");
1233                 }
1234                 break;
1235
1236         case LFUN_ALL_CHANGES_ACCEPT:
1237                 // select complete document
1238                 cur.reset(buffer_.inset());
1239                 cur.selHandle(true);
1240                 buffer_.text().cursorBottom(cur);
1241                 // accept everything in a single step to support atomic undo
1242                 buffer_.text().acceptOrRejectChanges(cur, Text::ACCEPT);
1243                 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1244                 processUpdateFlags(Update::Force | Update::FitCursor);
1245                 break;
1246
1247         case LFUN_ALL_CHANGES_REJECT:
1248                 // select complete document
1249                 cur.reset(buffer_.inset());
1250                 cur.selHandle(true);
1251                 buffer_.text().cursorBottom(cur);
1252                 // reject everything in a single step to support atomic undo
1253                 // Note: reject does not work recursively; the user may have to repeat the operation
1254                 buffer_.text().acceptOrRejectChanges(cur, Text::REJECT);
1255                 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1256                 processUpdateFlags(Update::Force | Update::FitCursor);
1257                 break;
1258
1259         case LFUN_WORD_FIND_FORWARD:
1260         case LFUN_WORD_FIND_BACKWARD: {
1261                 static docstring last_search;
1262                 docstring searched_string;
1263
1264                 if (!cmd.argument().empty()) {
1265                         last_search = cmd.argument();
1266                         searched_string = cmd.argument();
1267                 } else {
1268                         searched_string = last_search;
1269                 }
1270
1271                 if (searched_string.empty())
1272                         break;
1273
1274                 bool const fw = cmd.action == LFUN_WORD_FIND_FORWARD;
1275                 docstring const data =
1276                         find2string(searched_string, true, false, fw);
1277                 find(this, FuncRequest(LFUN_WORD_FIND, data));
1278                 break;
1279         }
1280
1281         case LFUN_WORD_FIND: {
1282                 FuncRequest req = cmd;
1283                 if (cmd.argument().empty() && !d->search_request_cache_.argument().empty())
1284                         req = d->search_request_cache_;
1285                 if (req.argument().empty()) {
1286                         theLyXFunc().dispatch(FuncRequest(LFUN_DIALOG_SHOW, "findreplace"));
1287                         break;
1288                 }
1289                 if (find(this, req))
1290                         showCursor();
1291                 else
1292                         message(_("String not found!"));
1293                 d->search_request_cache_ = req;
1294                 break;
1295         }
1296
1297         case LFUN_WORD_REPLACE: {
1298                 bool has_deleted = false;
1299                 if (cur.selection()) {
1300                         DocIterator beg = cur.selectionBegin();
1301                         DocIterator end = cur.selectionEnd();
1302                         if (beg.pit() == end.pit()) {
1303                                 for (pos_type p = beg.pos() ; p < end.pos() ; ++p) {
1304                                         if (cur.paragraph().isDeleted(p))
1305                                                 has_deleted = true;
1306                                 }
1307                         }
1308                 }
1309                 replace(this, cmd, has_deleted);
1310                 break;
1311         }
1312
1313         case LFUN_WORD_FINDADV:
1314                 findAdv(this, cmd);
1315                 break;
1316
1317         case LFUN_MARK_OFF:
1318                 cur.clearSelection();
1319                 cur.message(from_utf8(N_("Mark off")));
1320                 break;
1321
1322         case LFUN_MARK_ON:
1323                 cur.clearSelection();
1324                 cur.setMark(true);
1325                 cur.message(from_utf8(N_("Mark on")));
1326                 break;
1327
1328         case LFUN_MARK_TOGGLE:
1329                 cur.setSelection(false);
1330                 if (cur.mark()) {
1331                         cur.setMark(false);
1332                         cur.message(from_utf8(N_("Mark removed")));
1333                 } else {
1334                         cur.setMark(true);
1335                         cur.message(from_utf8(N_("Mark set")));
1336                 }
1337                 cur.resetAnchor();
1338                 break;
1339
1340         case LFUN_SCREEN_SHOW_CURSOR:
1341                 showCursor();
1342                 break;
1343         
1344         case LFUN_SCREEN_RECENTER:
1345                 recenter();
1346                 break;
1347
1348         case LFUN_BIBTEX_DATABASE_ADD: {
1349                 Cursor tmpcur = cur;
1350                 findInset(tmpcur, BIBTEX_CODE, false);
1351                 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1352                                                 BIBTEX_CODE);
1353                 if (inset) {
1354                         if (inset->addDatabase(cmd.argument()))
1355                                 buffer_.updateBibfilesCache();
1356                 }
1357                 break;
1358         }
1359
1360         case LFUN_BIBTEX_DATABASE_DEL: {
1361                 Cursor tmpcur = cur;
1362                 findInset(tmpcur, BIBTEX_CODE, false);
1363                 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1364                                                 BIBTEX_CODE);
1365                 if (inset) {
1366                         if (inset->delDatabase(cmd.argument()))
1367                                 buffer_.updateBibfilesCache();
1368                 }
1369                 break;
1370         }
1371
1372         case LFUN_STATISTICS: {
1373                 DocIterator from, to;
1374                 if (cur.selection()) {
1375                         from = cur.selectionBegin();
1376                         to = cur.selectionEnd();
1377                 } else {
1378                         from = doc_iterator_begin(&buffer_);
1379                         to = doc_iterator_end(&buffer_);
1380                 }
1381                 int const words = countWords(from, to);
1382                 int const chars = countChars(from, to, false);
1383                 int const chars_blanks = countChars(from, to, true);
1384                 docstring message;
1385                 if (cur.selection())
1386                         message = _("Statistics for the selection:");
1387                 else
1388                         message = _("Statistics for the document:");
1389                 message += "\n\n";
1390                 if (words != 1)
1391                         message += bformat(_("%1$d words"), words);
1392                 else
1393                         message += _("One word");
1394                 message += "\n";
1395                 if (chars_blanks != 1)
1396                         message += bformat(_("%1$d characters (including blanks)"),
1397                                           chars_blanks);
1398                 else
1399                         message += _("One character (including blanks)");
1400                 message += "\n";
1401                 if (chars != 1)
1402                         message += bformat(_("%1$d characters (excluding blanks)"),
1403                                           chars);
1404                 else
1405                         message += _("One character (excluding blanks)");
1406
1407                 Alert::information(_("Statistics"), message);
1408         }
1409                 break;
1410
1411         case LFUN_BUFFER_TOGGLE_COMPRESSION:
1412                 // turn compression on/off
1413                 buffer_.params().compressed = !buffer_.params().compressed;
1414                 break;
1415
1416         case LFUN_LABEL_COPY_AS_REF: {
1417                 // if there is an inset at cursor, try to copy it
1418                 Inset * inset = &cur.inset();
1419                 if (!inset || !inset->asInsetMath())
1420                         inset = cur.nextInset();
1421                 if (inset) {
1422                         FuncRequest tmpcmd = cmd;
1423                         inset->dispatch(cur, tmpcmd);
1424                 }
1425                 if (!cur.result().dispatched())
1426                         // It did not work too; no action needed.
1427                         break;
1428                 cur.clearSelection();
1429                 processUpdateFlags(Update::SinglePar | Update::FitCursor);
1430                 break;
1431         }
1432
1433         case LFUN_NEXT_INSET_MODIFY: {
1434                 // create the the real function we want to invoke
1435                 FuncRequest tmpcmd = cmd;
1436                 tmpcmd.action = LFUN_INSET_MODIFY;
1437                 // if there is an inset at cursor, see whether it
1438                 // can be modified.
1439                 Inset * inset = cur.nextInset();
1440                 if (inset) {
1441                         cur.recordUndo();
1442                         inset->dispatch(cur, tmpcmd);
1443                 }
1444                 // if it did not work, try the underlying inset.
1445                 if (!inset || !cur.result().dispatched()) {
1446                         cur.recordUndo();
1447                         cur.dispatch(tmpcmd);
1448                 }
1449
1450                 if (!cur.result().dispatched())
1451                         // It did not work too; no action needed.
1452                         break;
1453                 cur.clearSelection();
1454                 processUpdateFlags(Update::Force | Update::FitCursor);
1455                 break;
1456         }
1457
1458         case LFUN_SCREEN_UP:
1459         case LFUN_SCREEN_DOWN: {
1460                 Point p = getPos(cur, cur.boundary());
1461                 // This code has been commented out to enable to scroll down a
1462                 // document, even if there are large insets in it (see bug #5465).
1463                 /*if (p.y_ < 0 || p.y_ > height_) {
1464                         // The cursor is off-screen so recenter before proceeding.
1465                         showCursor();
1466                         p = getPos(cur, cur.boundary());
1467                 }*/
1468                 int const scrolled = scroll(cmd.action == LFUN_SCREEN_UP
1469                         ? -height_ : height_);
1470                 if (cmd.action == LFUN_SCREEN_UP && scrolled > -height_)
1471                         p = Point(0, 0);
1472                 if (cmd.action == LFUN_SCREEN_DOWN && scrolled < height_)
1473                         p = Point(width_, height_);
1474                 Cursor old = cur;
1475                 bool const in_texted = cur.inTexted();
1476                 cur.reset(buffer_.inset());
1477                 updateMetrics();
1478                 buffer_.changed();
1479                 d->text_metrics_[&buffer_.text()].editXY(cur, p.x_, p.y_,
1480                         true, cmd.action == LFUN_SCREEN_UP); 
1481                 //FIXME: what to do with cur.x_target()?
1482                 bool update = in_texted && cur.bv().checkDepm(cur, old);
1483                 cur.finishUndo();
1484                 if (update)
1485                         processUpdateFlags(Update::Force | Update::FitCursor);
1486                 break;
1487         }
1488
1489         case LFUN_SCROLL:
1490                 lfunScroll(cmd);
1491                 break;
1492
1493         case LFUN_SCREEN_UP_SELECT: {
1494                 cur.selHandle(true);
1495                 if (isTopScreen()) {
1496                         lyx::dispatch(FuncRequest(LFUN_BUFFER_BEGIN_SELECT));
1497                         cur.finishUndo();
1498                         break;
1499                 }
1500                 int y = getPos(cur, cur.boundary()).y_;
1501                 int const ymin = y - height_ + defaultRowHeight();
1502                 while (y > ymin && cur.up())
1503                         y = getPos(cur, cur.boundary()).y_;
1504
1505                 cur.finishUndo();
1506                 processUpdateFlags(Update::SinglePar | Update::FitCursor);
1507                 break;
1508         }
1509
1510         case LFUN_SCREEN_DOWN_SELECT: {
1511                 cur.selHandle(true);
1512                 if (isBottomScreen()) {
1513                         lyx::dispatch(FuncRequest(LFUN_BUFFER_END_SELECT));
1514                         cur.finishUndo();
1515                         break;
1516                 }
1517                 int y = getPos(cur, cur.boundary()).y_;
1518                 int const ymax = y + height_ - defaultRowHeight();
1519                 while (y < ymax && cur.down())
1520                         y = getPos(cur, cur.boundary()).y_;
1521
1522                 cur.finishUndo();
1523                 processUpdateFlags(Update::SinglePar | Update::FitCursor);
1524                 break;
1525         }
1526
1527         // This could be rewriten using some command like forall <insetname> <command>
1528         // once the insets refactoring is done.
1529         case LFUN_NOTES_MUTATE: {
1530                 if (cmd.argument().empty())
1531                         break;
1532
1533                 if (mutateNotes(cur, cmd.getArg(0), cmd.getArg(1))) {
1534                         processUpdateFlags(Update::Force);
1535                 }
1536                 break;
1537         }
1538
1539         case LFUN_ALL_INSETS_TOGGLE: {
1540                 string action;
1541                 string const name = split(to_utf8(cmd.argument()), action, ' ');
1542                 InsetCode const inset_code = insetCode(name);
1543
1544                 FuncRequest fr(LFUN_INSET_TOGGLE, action);
1545
1546                 Inset & inset = cur.buffer()->inset();
1547                 InsetIterator it  = inset_iterator_begin(inset);
1548                 InsetIterator const end = inset_iterator_end(inset);
1549                 for (; it != end; ++it) {
1550                         if (it->asInsetCollapsable()
1551                             && (inset_code == NO_CODE
1552                             || inset_code == it->lyxCode())) {
1553                                 Cursor tmpcur = cur;
1554                                 tmpcur.pushBackward(*it);
1555                                 it->dispatch(tmpcur, fr);
1556                         }
1557                 }
1558                 processUpdateFlags(Update::Force | Update::FitCursor);
1559                 break;
1560         }
1561
1562         case LFUN_BRANCH_ADD_INSERT: {
1563                 docstring branch_name = from_utf8(cmd.getArg(0));
1564                 if (branch_name.empty())
1565                         if (!Alert::askForText(branch_name, _("Branch name")) ||
1566                                                 branch_name.empty())
1567                                 break;
1568
1569                 DispatchResult drtmp;
1570                 buffer_.dispatch(FuncRequest(LFUN_BRANCH_ADD, branch_name), drtmp);
1571                 if (drtmp.error()) {
1572                         Alert::warning(_("Branch already exists"), drtmp.message());
1573                         break;
1574                 }
1575                 BranchList & branch_list = buffer_.params().branchlist();
1576                 Branch const * branch = branch_list.find(branch_name);
1577                 string const x11hexname = X11hexname(branch->color());
1578                 docstring const str = branch_name + ' ' + from_ascii(x11hexname);
1579                 lyx::dispatch(FuncRequest(LFUN_SET_COLOR, str));
1580                 lyx::dispatch(FuncRequest(LFUN_BRANCH_INSERT, branch_name));
1581                 break;
1582         }
1583
1584         case LFUN_KEYMAP_OFF:
1585                 getIntl().keyMapOn(false);
1586                 break;
1587
1588         case LFUN_KEYMAP_PRIMARY:
1589                 getIntl().keyMapPrim();
1590                 break;
1591
1592         case LFUN_KEYMAP_SECONDARY:
1593                 getIntl().keyMapSec();
1594                 break;
1595
1596         case LFUN_KEYMAP_TOGGLE:
1597                 getIntl().toggleKeyMap();
1598                 break;
1599
1600         default:
1601                 return false;
1602         }
1603
1604         return true;
1605 }
1606
1607
1608 docstring const BufferView::requestSelection()
1609 {
1610         Cursor & cur = d->cursor_;
1611
1612         LYXERR(Debug::SELECTION, "requestSelection: cur.selection: " << cur.selection());
1613         if (!cur.selection()) {
1614                 d->xsel_cache_.set = false;
1615                 return docstring();
1616         }
1617
1618         LYXERR(Debug::SELECTION, "requestSelection: xsel_cache.set: " << d->xsel_cache_.set);
1619         if (!d->xsel_cache_.set ||
1620             cur.top() != d->xsel_cache_.cursor ||
1621             cur.anchor_.top() != d->xsel_cache_.anchor)
1622         {
1623                 d->xsel_cache_.cursor = cur.top();
1624                 d->xsel_cache_.anchor = cur.anchor_.top();
1625                 d->xsel_cache_.set = cur.selection();
1626                 return cur.selectionAsString(false);
1627         }
1628         return docstring();
1629 }
1630
1631
1632 void BufferView::clearSelection()
1633 {
1634         d->cursor_.clearSelection();
1635         // Clear the selection buffer. Otherwise a subsequent
1636         // middle-mouse-button paste would use the selection buffer,
1637         // not the more current external selection.
1638         cap::clearSelection();
1639         d->xsel_cache_.set = false;
1640         // The buffer did not really change, but this causes the
1641         // redraw we need because we cleared the selection above.
1642         buffer_.changed();
1643 }
1644
1645
1646 void BufferView::resize(int width, int height)
1647 {
1648         // Update from work area
1649         width_ = width;
1650         height_ = height;
1651
1652         // Clear the paragraph height cache.
1653         d->par_height_.clear();
1654         // Redo the metrics.
1655         updateMetrics();
1656 }
1657
1658
1659 Inset const * BufferView::getCoveringInset(Text const & text,
1660                 int x, int y) const
1661 {
1662         TextMetrics & tm = d->text_metrics_[&text];
1663         Inset * inset = tm.checkInsetHit(x, y);
1664         if (!inset)
1665                 return 0;
1666
1667         if (!inset->descendable())
1668                 // No need to go further down if the inset is not
1669                 // descendable.
1670                 return inset;
1671
1672         size_t cell_number = inset->nargs();
1673         // Check all the inner cell.
1674         for (size_t i = 0; i != cell_number; ++i) {
1675                 Text const * inner_text = inset->getText(i);
1676                 if (inner_text) {
1677                         // Try deeper.
1678                         Inset const * inset_deeper =
1679                                 getCoveringInset(*inner_text, x, y);
1680                         if (inset_deeper)
1681                                 return inset_deeper;
1682                 }
1683         }
1684
1685         return inset;
1686 }
1687
1688
1689 void BufferView::mouseEventDispatch(FuncRequest const & cmd0)
1690 {
1691         //lyxerr << "[ cmd0 " << cmd0 << "]" << endl;
1692
1693         // This is only called for mouse related events including
1694         // LFUN_FILE_OPEN generated by drag-and-drop.
1695         FuncRequest cmd = cmd0;
1696
1697         Cursor old = cursor();
1698         Cursor cur(*this);
1699         cur.push(buffer_.inset());
1700         cur.setSelection(d->cursor_.selection());
1701
1702         // Either the inset under the cursor or the
1703         // surrounding Text will handle this event.
1704
1705         // make sure we stay within the screen...
1706         cmd.y = min(max(cmd.y, -1), height_);
1707
1708         if (cmd.action == LFUN_MOUSE_MOTION && cmd.button() == mouse_button::none) {
1709
1710                 // Get inset under mouse, if there is one.
1711                 Inset const * covering_inset =
1712                         getCoveringInset(buffer_.text(), cmd.x, cmd.y);
1713                 if (covering_inset == d->last_inset_)
1714                         // Same inset, no need to do anything...
1715                         return;
1716
1717                 bool need_redraw = false;
1718                 // const_cast because of setMouseHover().
1719                 Inset * inset = const_cast<Inset *>(covering_inset);
1720                 if (d->last_inset_)
1721                         // Remove the hint on the last hovered inset (if any).
1722                         need_redraw |= d->last_inset_->setMouseHover(false);
1723                 if (inset)
1724                         // Highlighted the newly hovered inset (if any).
1725                         need_redraw |= inset->setMouseHover(true);
1726                 d->last_inset_ = inset;
1727                 if (!need_redraw)
1728                         return;
1729
1730                 LYXERR(Debug::PAINTING, "Mouse hover detected at: ("
1731                         << cmd.x << ", " << cmd.y << ")");
1732
1733                 d->update_strategy_ = DecorationUpdate;
1734
1735                 // This event (moving without mouse click) is not passed further.
1736                 // This should be changed if it is further utilized.
1737                 buffer_.changed();
1738                 return;
1739         }
1740
1741         // Build temporary cursor.
1742         Inset * inset = d->text_metrics_[&buffer_.text()].editXY(cur, cmd.x, cmd.y);
1743
1744         // Put anchor at the same position.
1745         cur.resetAnchor();
1746
1747         cur.beginUndoGroup();
1748
1749         // Try to dispatch to an non-editable inset near this position
1750         // via the temp cursor. If the inset wishes to change the real
1751         // cursor it has to do so explicitly by using
1752         //  cur.bv().cursor() = cur;  (or similar)
1753         if (inset)
1754                 inset->dispatch(cur, cmd);
1755
1756         // Now dispatch to the temporary cursor. If the real cursor should
1757         // be modified, the inset's dispatch has to do so explicitly.
1758         if (!inset || !cur.result().dispatched())
1759                 cur.dispatch(cmd);
1760
1761         cur.endUndoGroup();
1762
1763         // Notify left insets
1764         if (cur != old) {
1765                 old.fixIfBroken();
1766                 bool badcursor = notifyCursorLeavesOrEnters(old, cur);
1767                 if (badcursor)
1768                         cursor().fixIfBroken();
1769         }
1770         
1771         // Do we have a selection?
1772         theSelection().haveSelection(cursor().selection());
1773
1774         // If the command has been dispatched,
1775         if (cur.result().dispatched() || cur.result().update())
1776                 processUpdateFlags(cur.result().update());
1777 }
1778
1779
1780 void BufferView::lfunScroll(FuncRequest const & cmd)
1781 {
1782         string const scroll_type = cmd.getArg(0);
1783         int const scroll_step = 
1784                 (scroll_type == "line") ? d->scrollbarParameters_.single_step
1785                 : (scroll_type == "page") ? d->scrollbarParameters_.page_step : 0;
1786         if (scroll_step == 0)
1787                 return;
1788         string const scroll_quantity = cmd.getArg(1);
1789         if (scroll_quantity == "up")
1790                 scrollUp(scroll_step);
1791         else if (scroll_quantity == "down")
1792                 scrollDown(scroll_step);
1793         else {
1794                 int const scroll_value = convert<int>(scroll_quantity);
1795                 if (scroll_value)
1796                         scroll(scroll_step * scroll_value);
1797         }
1798         updateMetrics();
1799         buffer_.changed();
1800 }
1801
1802
1803 int BufferView::minVisiblePart()
1804 {
1805         return 2 * defaultRowHeight();
1806 }
1807
1808
1809 int BufferView::scroll(int y)
1810 {
1811         if (y > 0)
1812                 return scrollDown(y);
1813         if (y < 0)
1814                 return scrollUp(-y);
1815         return 0;
1816 }
1817
1818
1819 int BufferView::scrollDown(int offset)
1820 {
1821         Text * text = &buffer_.text();
1822         TextMetrics & tm = d->text_metrics_[text];
1823         int const ymax = height_ + offset;
1824         while (true) {
1825                 pair<pit_type, ParagraphMetrics const *> last = tm.last();
1826                 int bottom_pos = last.second->position() + last.second->descent();
1827                 if (lyxrc.scroll_below_document)
1828                         bottom_pos += height_ - minVisiblePart();
1829                 if (last.first + 1 == int(text->paragraphs().size())) {
1830                         if (bottom_pos <= height_)
1831                                 return 0;
1832                         offset = min(offset, bottom_pos - height_);
1833                         break;
1834                 }
1835                 if (bottom_pos > ymax)
1836                         break;
1837                 tm.newParMetricsDown();
1838         }
1839         d->anchor_ypos_ -= offset;
1840         return -offset;
1841 }
1842
1843
1844 int BufferView::scrollUp(int offset)
1845 {
1846         Text * text = &buffer_.text();
1847         TextMetrics & tm = d->text_metrics_[text];
1848         int ymin = - offset;
1849         while (true) {
1850                 pair<pit_type, ParagraphMetrics const *> first = tm.first();
1851                 int top_pos = first.second->position() - first.second->ascent();
1852                 if (first.first == 0) {
1853                         if (top_pos >= 0)
1854                                 return 0;
1855                         offset = min(offset, - top_pos);
1856                         break;
1857                 }
1858                 if (top_pos < ymin)
1859                         break;
1860                 tm.newParMetricsUp();
1861         }
1862         d->anchor_ypos_ += offset;
1863         return offset;
1864 }
1865
1866
1867 void BufferView::setCursorFromRow(int row)
1868 {
1869         int tmpid = -1;
1870         int tmppos = -1;
1871
1872         buffer_.texrow().getIdFromRow(row, tmpid, tmppos);
1873
1874         d->cursor_.reset(buffer_.inset());
1875         if (tmpid == -1)
1876                 buffer_.text().setCursor(d->cursor_, 0, 0);
1877         else
1878                 buffer_.text().setCursor(d->cursor_, buffer_.getParFromID(tmpid).pit(), tmppos);
1879 }
1880
1881
1882 bool BufferView::setCursorFromInset(Inset const * inset)
1883 {
1884         // are we already there?
1885         if (cursor().nextInset() == inset)
1886                 return true;
1887
1888         // Inset is not at cursor position. Find it in the document.
1889         Cursor cur(*this);
1890         cur.reset(buffer().inset());
1891         while (cur && cur.nextInset() != inset)
1892                 cur.forwardInset();
1893
1894         if (cur) {
1895                 setCursor(cur);
1896                 return true;
1897         }
1898         return false;
1899 }
1900
1901
1902 void BufferView::gotoLabel(docstring const & label)
1903 {
1904         std::vector<Buffer const *> bufs = buffer().allRelatives();
1905         std::vector<Buffer const *>::iterator it = bufs.begin();
1906         for (; it != bufs.end(); ++it) {
1907                 Buffer const * buf = *it;
1908
1909                 // find label
1910                 Toc & toc = buf->tocBackend().toc("label");
1911                 TocIterator toc_it = toc.begin();
1912                 TocIterator end = toc.end();
1913                 for (; toc_it != end; ++toc_it) {
1914                         if (label == toc_it->str()) {
1915                                 dispatch(toc_it->action());
1916                                 return;
1917                         }
1918                 }
1919         }
1920 }
1921
1922
1923 TextMetrics const & BufferView::textMetrics(Text const * t) const
1924 {
1925         return const_cast<BufferView *>(this)->textMetrics(t);
1926 }
1927
1928
1929 TextMetrics & BufferView::textMetrics(Text const * t)
1930 {
1931         TextMetricsCache::iterator tmc_it  = d->text_metrics_.find(t);
1932         if (tmc_it == d->text_metrics_.end()) {
1933                 tmc_it = d->text_metrics_.insert(
1934                         make_pair(t, TextMetrics(this, const_cast<Text *>(t)))).first;
1935         }
1936         return tmc_it->second;
1937 }
1938
1939
1940 ParagraphMetrics const & BufferView::parMetrics(Text const * t,
1941                 pit_type pit) const
1942 {
1943         return textMetrics(t).parMetrics(pit);
1944 }
1945
1946
1947 int BufferView::workHeight() const
1948 {
1949         return height_;
1950 }
1951
1952
1953 void BufferView::setCursor(DocIterator const & dit)
1954 {
1955         d->cursor_.reset(buffer().inset());
1956         size_t const n = dit.depth();
1957         for (size_t i = 0; i < n; ++i)
1958                 dit[i].inset().edit(d->cursor_, true);
1959
1960         d->cursor_.setCursor(dit);
1961         d->cursor_.setSelection(false);
1962 }
1963
1964
1965 bool BufferView::checkDepm(Cursor & cur, Cursor & old)
1966 {
1967         // Would be wrong to delete anything if we have a selection.
1968         if (cur.selection())
1969                 return false;
1970
1971         bool need_anchor_change = false;
1972         bool changed = d->cursor_.text()->deleteEmptyParagraphMechanism(cur, old,
1973                 need_anchor_change);
1974
1975         if (need_anchor_change)
1976                 cur.resetAnchor();
1977
1978         if (!changed)
1979                 return false;
1980
1981         d->cursor_ = cur;
1982
1983         buffer_.updateLabels();
1984
1985         updateMetrics();
1986         buffer_.changed();
1987         return true;
1988 }
1989
1990
1991 bool BufferView::mouseSetCursor(Cursor & cur, bool select)
1992 {
1993         LASSERT(&cur.bv() == this, /**/);
1994
1995         if (!select)
1996                 // this event will clear selection so we save selection for
1997                 // persistent selection
1998                 cap::saveSelection(cursor());
1999
2000         // Has the cursor just left the inset?
2001         bool leftinset = (&d->cursor_.inset() != &cur.inset());
2002         if (leftinset)
2003                 d->cursor_.fixIfBroken();
2004
2005         // FIXME: shift-mouse selection doesn't work well across insets.
2006         bool do_selection = select && &d->cursor_.anchor().inset() == &cur.inset();
2007
2008         // do the dEPM magic if needed
2009         // FIXME: (1) move this to InsetText::notifyCursorLeaves?
2010         // FIXME: (2) if we had a working InsetText::notifyCursorLeaves,
2011         // the leftinset bool would not be necessary (badcursor instead).
2012         bool update = leftinset;
2013         if (!do_selection && d->cursor_.inTexted())
2014                 update |= checkDepm(cur, d->cursor_);
2015         d->cursor_.macroModeClose();
2016
2017         d->cursor_.resetAnchor();
2018         d->cursor_.setCursor(cur);
2019         d->cursor_.boundary(cur.boundary());
2020         if (do_selection)
2021                 d->cursor_.setSelection();
2022         else
2023                 d->cursor_.clearSelection();
2024
2025         d->cursor_.finishUndo();
2026         d->cursor_.setCurrentFont();
2027         return update;
2028 }
2029
2030
2031 void BufferView::putSelectionAt(DocIterator const & cur,
2032                                 int length, bool backwards)
2033 {
2034         d->cursor_.clearSelection();
2035
2036         setCursor(cur);
2037
2038         if (length) {
2039                 if (backwards) {
2040                         d->cursor_.pos() += length;
2041                         d->cursor_.setSelection(d->cursor_, -length);
2042                 } else
2043                         d->cursor_.setSelection(d->cursor_, length);
2044         }
2045         // Ensure a redraw happens in any case because the new selection could 
2046         // possibly be on the same screen as the previous selection.
2047         processUpdateFlags(Update::Force | Update::FitCursor);
2048 }
2049
2050
2051 Cursor & BufferView::cursor()
2052 {
2053         return d->cursor_;
2054 }
2055
2056
2057 Cursor const & BufferView::cursor() const
2058 {
2059         return d->cursor_;
2060 }
2061
2062
2063 pit_type BufferView::anchor_ref() const
2064 {
2065         return d->anchor_pit_;
2066 }
2067
2068
2069 bool BufferView::singleParUpdate()
2070 {
2071         Text & buftext = buffer_.text();
2072         pit_type const bottom_pit = d->cursor_.bottom().pit();
2073         TextMetrics & tm = textMetrics(&buftext);
2074         int old_height = tm.parMetrics(bottom_pit).height();
2075
2076         // make sure inline completion pointer is ok
2077         if (d->inlineCompletionPos_.fixIfBroken())
2078                 d->inlineCompletionPos_ = DocIterator();
2079
2080         // In Single Paragraph mode, rebreak only
2081         // the (main text, not inset!) paragraph containing the cursor.
2082         // (if this paragraph contains insets etc., rebreaking will
2083         // recursively descend)
2084         tm.redoParagraph(bottom_pit);
2085         ParagraphMetrics const & pm = tm.parMetrics(bottom_pit);                
2086         if (pm.height() != old_height)
2087                 // Paragraph height has changed so we cannot proceed to
2088                 // the singlePar optimisation.
2089                 return false;
2090
2091         d->update_strategy_ = SingleParUpdate;
2092
2093         LYXERR(Debug::PAINTING, "\ny1: " << pm.position() - pm.ascent()
2094                 << " y2: " << pm.position() + pm.descent()
2095                 << " pit: " << bottom_pit
2096                 << " singlepar: 1");
2097         return true;
2098 }
2099
2100
2101 void BufferView::updateMetrics()
2102 {
2103         if (height_ == 0 || width_ == 0)
2104                 return;
2105
2106         Text & buftext = buffer_.text();
2107         pit_type const npit = int(buftext.paragraphs().size());
2108
2109         // Clear out the position cache in case of full screen redraw,
2110         d->coord_cache_.clear();
2111
2112         // Clear out paragraph metrics to avoid having invalid metrics
2113         // in the cache from paragraphs not relayouted below
2114         // The complete text metrics will be redone.
2115         d->text_metrics_.clear();
2116
2117         TextMetrics & tm = textMetrics(&buftext);
2118
2119         // make sure inline completion pointer is ok
2120         if (d->inlineCompletionPos_.fixIfBroken())
2121                 d->inlineCompletionPos_ = DocIterator();
2122         
2123         if (d->anchor_pit_ >= npit)
2124                 // The anchor pit must have been deleted...
2125                 d->anchor_pit_ = npit - 1;
2126
2127         // Rebreak anchor paragraph.
2128         tm.redoParagraph(d->anchor_pit_);
2129         ParagraphMetrics & anchor_pm = tm.par_metrics_[d->anchor_pit_];
2130         
2131         // position anchor
2132         if (d->anchor_pit_ == 0) {
2133                 int scrollRange = d->scrollbarParameters_.max - d->scrollbarParameters_.min;
2134                 
2135                 // Complete buffer visible? Then it's easy.
2136                 if (scrollRange == 0)
2137                         d->anchor_ypos_ = anchor_pm.ascent();
2138         
2139                 // FIXME: Some clever handling needed to show
2140                 // the _first_ paragraph up to the top if the cursor is
2141                 // in the first line.
2142         }               
2143         anchor_pm.setPosition(d->anchor_ypos_);
2144
2145         LYXERR(Debug::PAINTING, "metrics: "
2146                 << " anchor pit = " << d->anchor_pit_
2147                 << " anchor ypos = " << d->anchor_ypos_);
2148
2149         // Redo paragraphs above anchor if necessary.
2150         int y1 = d->anchor_ypos_ - anchor_pm.ascent();
2151         // We are now just above the anchor paragraph.
2152         pit_type pit1 = d->anchor_pit_ - 1;
2153         for (; pit1 >= 0 && y1 >= 0; --pit1) {
2154                 tm.redoParagraph(pit1);
2155                 ParagraphMetrics & pm = tm.par_metrics_[pit1];
2156                 y1 -= pm.descent();
2157                 // Save the paragraph position in the cache.
2158                 pm.setPosition(y1);
2159                 y1 -= pm.ascent();
2160         }
2161
2162         // Redo paragraphs below the anchor if necessary.
2163         int y2 = d->anchor_ypos_ + anchor_pm.descent();
2164         // We are now just below the anchor paragraph.
2165         pit_type pit2 = d->anchor_pit_ + 1;
2166         for (; pit2 < npit && y2 <= height_; ++pit2) {
2167                 tm.redoParagraph(pit2);
2168                 ParagraphMetrics & pm = tm.par_metrics_[pit2];
2169                 y2 += pm.ascent();
2170                 // Save the paragraph position in the cache.
2171                 pm.setPosition(y2);
2172                 y2 += pm.descent();
2173         }
2174
2175         LYXERR(Debug::PAINTING, "Metrics: "
2176                 << " anchor pit = " << d->anchor_pit_
2177                 << " anchor ypos = " << d->anchor_ypos_
2178                 << " y1 = " << y1
2179                 << " y2 = " << y2
2180                 << " pit1 = " << pit1
2181                 << " pit2 = " << pit2);
2182
2183         d->update_strategy_ = FullScreenUpdate;
2184
2185         if (lyxerr.debugging(Debug::WORKAREA)) {
2186                 LYXERR(Debug::WORKAREA, "BufferView::updateMetrics");
2187                 d->coord_cache_.dump();
2188         }
2189 }
2190
2191
2192 void BufferView::insertLyXFile(FileName const & fname)
2193 {
2194         LASSERT(d->cursor_.inTexted(), /**/);
2195
2196         // Get absolute path of file and add ".lyx"
2197         // to the filename if necessary
2198         FileName filename = fileSearch(string(), fname.absFilename(), "lyx");
2199
2200         docstring const disp_fn = makeDisplayPath(filename.absFilename());
2201         // emit message signal.
2202         message(bformat(_("Inserting document %1$s..."), disp_fn));
2203
2204         docstring res;
2205         Buffer buf("", false);
2206         if (buf.loadLyXFile(filename)) {
2207                 ErrorList & el = buffer_.errorList("Parse");
2208                 // Copy the inserted document error list into the current buffer one.
2209                 el = buf.errorList("Parse");
2210                 buffer_.undo().recordUndo(d->cursor_);
2211                 cap::pasteParagraphList(d->cursor_, buf.paragraphs(),
2212                                              buf.params().documentClassPtr(), el);
2213                 res = _("Document %1$s inserted.");
2214         } else {
2215                 res = _("Could not insert document %1$s");
2216         }
2217
2218         updateMetrics();
2219         buffer_.changed();
2220         // emit message signal.
2221         message(bformat(res, disp_fn));
2222         buffer_.errors("Parse");
2223 }
2224
2225
2226 Point BufferView::coordOffset(DocIterator const & dit, bool boundary) const
2227 {
2228         int x = 0;
2229         int y = 0;
2230         int lastw = 0;
2231
2232         // Addup contribution of nested insets, from inside to outside,
2233         // keeping the outer paragraph for a special handling below
2234         for (size_t i = dit.depth() - 1; i >= 1; --i) {
2235                 CursorSlice const & sl = dit[i];
2236                 int xx = 0;
2237                 int yy = 0;
2238                 
2239                 // get relative position inside sl.inset()
2240                 sl.inset().cursorPos(*this, sl, boundary && (i + 1 == dit.depth()), xx, yy);
2241                 
2242                 // Make relative position inside of the edited inset relative to sl.inset()
2243                 x += xx;
2244                 y += yy;
2245                 
2246                 // In case of an RTL inset, the edited inset will be positioned to the left
2247                 // of xx:yy
2248                 if (sl.text()) {
2249                         bool boundary_i = boundary && i + 1 == dit.depth();
2250                         bool rtl = textMetrics(sl.text()).isRTL(sl, boundary_i);
2251                         if (rtl)
2252                                 x -= lastw;
2253                 }
2254
2255                 // remember width for the case that sl.inset() is positioned in an RTL inset
2256                 if (i && dit[i - 1].text()) {
2257                         // If this Inset is inside a Text Inset, retrieve the Dimension
2258                         // from the containing text instead of using Inset::dimension() which
2259                         // might not be implemented.
2260                         // FIXME (Abdel 23/09/2007): this is a bit messy because of the
2261                         // elimination of Inset::dim_ cache. This coordOffset() method needs
2262                         // to be rewritten in light of the new design.
2263                         Dimension const & dim = parMetrics(dit[i - 1].text(),
2264                                 dit[i - 1].pit()).insetDimension(&sl.inset());
2265                         lastw = dim.wid;
2266                 } else {
2267                         Dimension const dim = sl.inset().dimension(*this);
2268                         lastw = dim.wid;
2269                 }
2270                 
2271                 //lyxerr << "Cursor::getPos, i: "
2272                 // << i << " x: " << xx << " y: " << y << endl;
2273         }
2274
2275         // Add contribution of initial rows of outermost paragraph
2276         CursorSlice const & sl = dit[0];
2277         TextMetrics const & tm = textMetrics(sl.text());
2278         ParagraphMetrics const & pm = tm.parMetrics(sl.pit());
2279         LASSERT(!pm.rows().empty(), /**/);
2280         y -= pm.rows()[0].ascent();
2281 #if 1
2282         // FIXME: document this mess
2283         size_t rend;
2284         if (sl.pos() > 0 && dit.depth() == 1) {
2285                 int pos = sl.pos();
2286                 if (pos && boundary)
2287                         --pos;
2288 //              lyxerr << "coordOffset: boundary:" << boundary << " depth:" << dit.depth() << " pos:" << pos << " sl.pos:" << sl.pos() << endl;
2289                 rend = pm.pos2row(pos);
2290         } else
2291                 rend = pm.pos2row(sl.pos());
2292 #else
2293         size_t rend = pm.pos2row(sl.pos());
2294 #endif
2295         for (size_t rit = 0; rit != rend; ++rit)
2296                 y += pm.rows()[rit].height();
2297         y += pm.rows()[rend].ascent();
2298         
2299         TextMetrics const & bottom_tm = textMetrics(dit.bottom().text());
2300         
2301         // Make relative position from the nested inset now bufferview absolute.
2302         int xx = bottom_tm.cursorX(dit.bottom(), boundary && dit.depth() == 1);
2303         x += xx;
2304         
2305         // In the RTL case place the nested inset at the left of the cursor in 
2306         // the outer paragraph
2307         bool boundary_1 = boundary && 1 == dit.depth();
2308         bool rtl = bottom_tm.isRTL(dit.bottom(), boundary_1);
2309         if (rtl)
2310                 x -= lastw;
2311         
2312         return Point(x, y);
2313 }
2314
2315
2316 Point BufferView::getPos(DocIterator const & dit, bool boundary) const
2317 {
2318         if (!paragraphVisible(dit))
2319                 return Point(-1, -1);
2320
2321         CursorSlice const & bot = dit.bottom();
2322         TextMetrics const & tm = textMetrics(bot.text());
2323
2324         Point p = coordOffset(dit, boundary); // offset from outer paragraph
2325         p.y_ += tm.parMetrics(bot.pit()).position();
2326         return p;
2327 }
2328
2329
2330 bool BufferView::paragraphVisible(DocIterator const & dit) const
2331 {
2332         CursorSlice const & bot = dit.bottom();
2333         TextMetrics const & tm = textMetrics(bot.text());
2334
2335         return tm.contains(bot.pit());
2336 }
2337
2338
2339 void BufferView::cursorPosAndHeight(Point & p, int & h) const
2340 {
2341         Cursor const & cur = cursor();
2342         Font const font = cur.getFont();
2343         frontend::FontMetrics const & fm = theFontMetrics(font);
2344         int const asc = fm.maxAscent();
2345         int const des = fm.maxDescent();
2346         h = asc + des;
2347         p = getPos(cur, cur.boundary());
2348         p.y_ -= asc;
2349 }
2350
2351
2352 bool BufferView::cursorInView(Point const & p, int h) const
2353 {
2354         Cursor const & cur = cursor();
2355         // does the cursor touch the screen ?
2356         if (p.y_ + h < 0 || p.y_ >= workHeight() || !paragraphVisible(cur))
2357                 return false;
2358         return true;
2359 }
2360
2361
2362 void BufferView::draw(frontend::Painter & pain)
2363 {
2364         if (height_ == 0 || width_ == 0)
2365                 return;
2366         LYXERR(Debug::PAINTING, "\t\t*** START DRAWING ***");
2367
2368         Text & text = buffer_.text();
2369         TextMetrics const & tm = d->text_metrics_[&text];
2370         int const y = tm.first().second->position();
2371         PainterInfo pi(this, pain);
2372
2373         switch (d->update_strategy_) {
2374
2375         case NoScreenUpdate:
2376                 // If no screen painting is actually needed, only some the different
2377                 // coordinates of insets and paragraphs needs to be updated.
2378                 pi.full_repaint = true;
2379                 pi.pain.setDrawingEnabled(false);
2380                 tm.draw(pi, 0, y);
2381                 break;
2382
2383         case SingleParUpdate:
2384                 pi.full_repaint = false;
2385                 // In general, only the current row of the outermost paragraph
2386                 // will be redrawn. Particular cases where selection spans
2387                 // multiple paragraph are correctly detected in TextMetrics.
2388                 tm.draw(pi, 0, y);
2389                 break;
2390
2391         case DecorationUpdate:
2392                 // FIXME: We should also distinguish DecorationUpdate to avoid text
2393                 // drawing if possible. This is not possible to do easily right now
2394                 // because of the single backing pixmap.
2395
2396         case FullScreenUpdate:
2397                 // The whole screen, including insets, will be refreshed.
2398                 pi.full_repaint = true;
2399
2400                 // Clear background.
2401                 pain.fillRectangle(0, 0, width_, height_,
2402                         pi.backgroundColor(&buffer_.inset()));
2403
2404                 // Draw everything.
2405                 tm.draw(pi, 0, y);
2406
2407                 // and possibly grey out below
2408                 pair<pit_type, ParagraphMetrics const *> lastpm = tm.last();
2409                 int const y2 = lastpm.second->position() + lastpm.second->descent();
2410                 
2411                 if (y2 < height_) {
2412                         Color color = buffer().isInternal() 
2413                                 ? Color_background : Color_bottomarea;
2414                         pain.fillRectangle(0, y2, width_, height_ - y2, color);
2415                 }
2416                 break;
2417         }
2418         LYXERR(Debug::PAINTING, "\n\t\t*** END DRAWING  ***");
2419
2420         // The scrollbar needs an update.
2421         updateScrollbar();
2422
2423         // Normalize anchor for next time
2424         pair<pit_type, ParagraphMetrics const *> firstpm = tm.first();
2425         pair<pit_type, ParagraphMetrics const *> lastpm = tm.last();
2426         for (pit_type pit = firstpm.first; pit <= lastpm.first; ++pit) {
2427                 ParagraphMetrics const & pm = tm.parMetrics(pit);
2428                 if (pm.position() + pm.descent() > 0) {
2429                         d->anchor_pit_ = pit;
2430                         d->anchor_ypos_ = pm.position();
2431                         break;
2432                 }
2433         }
2434         LYXERR(Debug::PAINTING, "Found new anchor pit = " << d->anchor_pit_
2435                 << "  anchor ypos = " << d->anchor_ypos_);
2436 }
2437
2438
2439 void BufferView::message(docstring const & msg)
2440 {
2441         if (d->gui_)
2442                 d->gui_->message(msg);
2443 }
2444
2445
2446 void BufferView::showDialog(string const & name)
2447 {
2448         if (d->gui_)
2449                 d->gui_->showDialog(name, string());
2450 }
2451
2452
2453 void BufferView::showDialog(string const & name,
2454         string const & data, Inset * inset)
2455 {
2456         if (d->gui_)
2457                 d->gui_->showDialog(name, data, inset);
2458 }
2459
2460
2461 void BufferView::updateDialog(string const & name, string const & data)
2462 {
2463         if (d->gui_)
2464                 d->gui_->updateDialog(name, data);
2465 }
2466
2467
2468 void BufferView::setGuiDelegate(frontend::GuiBufferViewDelegate * gui)
2469 {
2470         d->gui_ = gui;
2471 }
2472
2473
2474 // FIXME: Move this out of BufferView again
2475 docstring BufferView::contentsOfPlaintextFile(FileName const & fname)
2476 {
2477         if (!fname.isReadableFile()) {
2478                 docstring const error = from_ascii(strerror(errno));
2479                 docstring const file = makeDisplayPath(fname.absFilename(), 50);
2480                 docstring const text =
2481                   bformat(_("Could not read the specified document\n"
2482                             "%1$s\ndue to the error: %2$s"), file, error);
2483                 Alert::error(_("Could not read file"), text);
2484                 return docstring();
2485         }
2486
2487         if (!fname.isReadableFile()) {
2488                 docstring const file = makeDisplayPath(fname.absFilename(), 50);
2489                 docstring const text =
2490                   bformat(_("%1$s\n is not readable."), file);
2491                 Alert::error(_("Could not open file"), text);
2492                 return docstring();
2493         }
2494
2495         // FIXME UNICODE: We don't know the encoding of the file
2496         docstring file_content = fname.fileContents("UTF-8");
2497         if (file_content.empty()) {
2498                 Alert::error(_("Reading not UTF-8 encoded file"),
2499                              _("The file is not UTF-8 encoded.\n"
2500                                "It will be read as local 8Bit-encoded.\n"
2501                                "If this does not give the correct result\n"
2502                                "then please change the encoding of the file\n"
2503                                "to UTF-8 with a program other than LyX.\n"));
2504                 file_content = fname.fileContents("local8bit");
2505         }
2506
2507         return normalize_c(file_content);
2508 }
2509
2510
2511 void BufferView::insertPlaintextFile(FileName const & f, bool asParagraph)
2512 {
2513         docstring const tmpstr = contentsOfPlaintextFile(f);
2514
2515         if (tmpstr.empty())
2516                 return;
2517
2518         Cursor & cur = cursor();
2519         cap::replaceSelection(cur);
2520         buffer_.undo().recordUndo(cur);
2521         if (asParagraph)
2522                 cur.innerText()->insertStringAsParagraphs(cur, tmpstr, cur.current_font);
2523         else
2524                 cur.innerText()->insertStringAsLines(cur, tmpstr, cur.current_font);
2525
2526         updateMetrics();
2527         buffer_.changed();
2528 }
2529
2530
2531 docstring const & BufferView::inlineCompletion() const
2532 {
2533         return d->inlineCompletion_;
2534 }
2535
2536
2537 size_t const & BufferView::inlineCompletionUniqueChars() const
2538 {
2539         return d->inlineCompletionUniqueChars_;
2540 }
2541
2542
2543 DocIterator const & BufferView::inlineCompletionPos() const
2544 {
2545         return d->inlineCompletionPos_;
2546 }
2547
2548
2549 bool samePar(DocIterator const & a, DocIterator const & b)
2550 {
2551         if (a.empty() && b.empty())
2552                 return true;
2553         if (a.empty() || b.empty())
2554                 return false;
2555         if (a.depth() != b.depth())
2556                 return false;
2557         return &a.innerParagraph() == &b.innerParagraph();
2558 }
2559
2560
2561 void BufferView::setInlineCompletion(Cursor & cur, DocIterator const & pos, 
2562         docstring const & completion, size_t uniqueChars)
2563 {
2564         uniqueChars = min(completion.size(), uniqueChars);
2565         bool changed = d->inlineCompletion_ != completion
2566                 || d->inlineCompletionUniqueChars_ != uniqueChars;
2567         bool singlePar = true;
2568         d->inlineCompletion_ = completion;
2569         d->inlineCompletionUniqueChars_ = min(completion.size(), uniqueChars);
2570         
2571         //lyxerr << "setInlineCompletion pos=" << pos << " completion=" << completion << " uniqueChars=" << uniqueChars << std::endl;
2572         
2573         // at new position?
2574         DocIterator const & old = d->inlineCompletionPos_;
2575         if (old != pos) {
2576                 //lyxerr << "inlineCompletionPos changed" << std::endl;
2577                 // old or pos are in another paragraph?
2578                 if ((!samePar(cur, pos) && !pos.empty())
2579                     || (!samePar(cur, old) && !old.empty())) {
2580                         singlePar = false;
2581                         //lyxerr << "different paragraph" << std::endl;
2582                 }
2583                 d->inlineCompletionPos_ = pos;
2584         }
2585         
2586         // set update flags
2587         if (changed) {
2588                 if (singlePar && !(cur.disp_.update() & Update::Force))
2589                         cur.updateFlags(cur.disp_.update() | Update::SinglePar);
2590                 else
2591                         cur.updateFlags(cur.disp_.update() | Update::Force);
2592         }
2593 }
2594
2595 } // namespace lyx