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