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