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