]> git.lyx.org Git - features.git/blob - src/BufferView.cpp
Fix bug 3171: switching document jumps always back to last saved bookmark
[features.git] / src / BufferView.cpp
1 /**
2  * \file BufferView.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Alfredo Braunstein
7  * \author Lars Gullik Bjønnes
8  * \author John Levon
9  * \author André Pönitz
10  * \author Jürgen Vigna
11  *
12  * Full author contact details are available in file CREDITS.
13  */
14
15 #include <config.h>
16
17 #include "BufferView.h"
18
19 #include "Buffer.h"
20 #include "buffer_funcs.h"
21 #include "BufferList.h"
22 #include "BufferParams.h"
23 #include "bufferview_funcs.h"
24 #include "CoordCache.h"
25 #include "CutAndPaste.h"
26 #include "debug.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 "gettext.h"
34 #include "Intl.h"
35 #include "InsetIterator.h"
36 #include "Language.h"
37 #include "LaTeXFeatures.h"
38 #include "callback.h" // added for Dispatch functions
39 #include "LyX.h"
40 #include "lyxfind.h"
41 #include "LyXFunc.h"
42 #include "Layout.h"
43 #include "Text.h"
44 #include "TextClass.h"
45 #include "LyXRC.h"
46 #include "Session.h"
47 #include "Paragraph.h"
48 #include "paragraph_funcs.h"
49 #include "ParagraphParameters.h"
50 #include "ParIterator.h"
51 #include "TexRow.h"
52 #include "toc.h"
53 #include "Undo.h"
54 #include "VSpace.h"
55 #include "WordLangTuple.h"
56 #include "MetricsInfo.h"
57
58 #include "insets/InsetBibtex.h"
59 #include "insets/InsetCommand.h" // ChangeRefs
60 #include "insets/InsetRef.h"
61 #include "insets/InsetText.h"
62
63 #include "frontends/alert.h"
64 #include "frontends/FileDialog.h"
65 #include "frontends/FontMetrics.h"
66
67 #include "graphics/Previews.h"
68
69 #include "support/convert.h"
70 #include "support/FileFilterList.h"
71 #include "support/filetools.h"
72 #include "support/Package.h"
73 #include "support/types.h"
74
75 #include <boost/bind.hpp>
76 #include <boost/current_function.hpp>
77
78 #include <functional>
79 #include <vector>
80
81
82 namespace lyx {
83
84 using support::addPath;
85 using support::bformat;
86 using support::FileFilterList;
87 using support::FileName;
88 using support::fileSearch;
89 using support::isDirWriteable;
90 using support::isFileReadable;
91 using support::makeDisplayPath;
92 using support::package;
93
94 using std::distance;
95 using std::endl;
96 using std::istringstream;
97 using std::make_pair;
98 using std::min;
99 using std::max;
100 using std::mem_fun_ref;
101 using std::string;
102 using std::vector;
103
104 namespace Alert = frontend::Alert;
105
106 namespace {
107
108 /// Return an inset of this class if it exists at the current cursor position
109 template <class T>
110 T * getInsetByCode(Cursor & cur, Inset::Code code)
111 {
112         T * inset = 0;
113         DocIterator it = cur;
114         if (it.nextInset() &&
115             it.nextInset()->lyxCode() == code) {
116                 inset = static_cast<T*>(it.nextInset());
117         }
118         return inset;
119 }
120
121 } // anon namespace
122
123
124 BufferView::BufferView()
125         : width_(0), height_(0), buffer_(0), wh_(0),
126           cursor_(*this),
127           multiparsel_cache_(false), anchor_ref_(0), offset_ref_(0),
128           intl_(new Intl), last_inset_(0)
129 {
130         xsel_cache_.set = false;
131         intl_->initKeyMapper(lyxrc.use_kbmap);
132 }
133
134
135 BufferView::~BufferView()
136 {
137 }
138
139
140 Buffer * BufferView::buffer() const
141 {
142         return buffer_;
143 }
144
145
146 void BufferView::setBuffer(Buffer * b)
147 {
148         LYXERR(Debug::INFO) << BOOST_CURRENT_FUNCTION
149                             << "[ b = " << b << "]" << endl;
150
151         if (buffer_) {
152                 // Save the actual cursor position and anchor inside the
153                 // buffer so that it can be restored in case we rechange
154                 // to this buffer later on.
155                 buffer_->saveCursor(cursor_.selectionBegin(),
156                                     cursor_.selectionEnd());
157                 // update bookmark pit of the current buffer before switch
158                 for (size_t i = 0; i < LyX::ref().session().bookmarks().size(); ++i) {
159                         BookmarksSection::Bookmark const & bm = LyX::ref().session().bookmarks().bookmark(i);
160                         if (buffer()->fileName() != bm.filename.absFilename())
161                                 continue;
162                         // if top_id or bottom_pit, bottom_pos has been changed, update bookmark
163                         // see http://bugzilla.lyx.org/show_bug.cgi?id=3092
164                         pit_type new_pit;
165                         pos_type new_pos;
166                         int new_id;
167                         boost::tie(new_pit, new_pos, new_id) = moveToPosition(bm.bottom_pit, bm.bottom_pos, bm.top_id, bm.top_pos);
168                         if (bm.bottom_pit != new_pit || bm.bottom_pos != new_pos || bm.top_id != new_id )
169                                 const_cast<BookmarksSection::Bookmark &>(bm).updatePos(new_pit, new_pos, new_id);
170                 }
171                 // current buffer is going to be switched-off, save cursor pos
172                 // Ideally, the whole cursor stack should be saved, but session
173                 // currently can only handle bottom (whole document) level pit and pos.
174                 // That is to say, if a cursor is in a nested inset, it will be
175                 // restore to the left of the top level inset.
176                 LyX::ref().session().lastFilePos().save(FileName(buffer_->fileName()),
177                         boost::tie(cursor_.bottom().pit(), cursor_.bottom().pos()) );
178         }
179
180         // If we're quitting lyx, don't bother updating stuff
181         if (quitting) {
182                 buffer_ = 0;
183                 return;
184         }
185
186         //FIXME Fix for bug 3440 is here.
187         // If we are closing current buffer, switch to the first in
188         // buffer list.
189         if (!b) {
190                 LYXERR(Debug::INFO) << BOOST_CURRENT_FUNCTION
191                                     << " No Buffer!" << endl;
192                 // We are closing the buffer, use the first buffer as current
193                 //FIXME 3440
194                 // if (last_buffer_) buffer_ = last_buffer_;
195                 // also check that this is in theBufferList()?
196                 buffer_ = theBufferList().first();
197         } else {
198                 //FIXME 3440
199                 // last_buffer = buffer_;
200                 // Set current buffer
201                 buffer_ = b;
202         }
203
204         // Reset old cursor
205         cursor_ = Cursor(*this);
206         anchor_ref_ = 0;
207         offset_ref_ = 0;
208
209         if (!buffer_)
210                 return;
211
212         LYXERR(Debug::INFO) << BOOST_CURRENT_FUNCTION
213                                         << "Buffer addr: " << buffer_ << endl;
214         cursor_.push(buffer_->inset());
215         cursor_.resetAnchor();
216         buffer_->text().setCurrentFont(cursor_);
217
218         // Update the metrics now that we have a proper Cursor.
219         updateMetrics(false);
220
221         // FIXME: This code won't be needed once we switch to
222         // "one Buffer" / "one BufferView".
223         if (buffer_->getCursor().size() > 0 &&
224                         buffer_->getAnchor().size() > 0)
225         {
226                 cursor_.setCursor(buffer_->getAnchor().asDocIterator(&(buffer_->inset())));
227                 cursor_.resetAnchor();
228                 cursor_.setCursor(buffer_->getCursor().asDocIterator(&(buffer_->inset())));
229                 cursor_.setSelection();
230                 // do not set selection to the new buffer because we
231                 // only paste recent selection.
232
233                 // Make sure that the restored cursor is not broken. This can happen for
234                 // example if this Buffer has been modified by another view.
235                 cursor_.fixIfBroken();
236
237                 if (fitCursor())
238                         // Update the metrics if the cursor new position was off screen.
239                         updateMetrics(false);
240         }
241
242         if (graphics::Previews::status() != LyXRC::PREVIEW_OFF)
243                 graphics::Previews::get().generateBufferPreviews(*buffer_);
244 }
245
246
247 void BufferView::resize()
248 {
249         if (!buffer_)
250                 return;
251
252         LYXERR(Debug::DEBUG) << BOOST_CURRENT_FUNCTION << endl;
253
254         updateMetrics(false);
255 }
256
257
258 bool BufferView::fitCursor()
259 {
260         if (bv_funcs::status(this, cursor_) == bv_funcs::CUR_INSIDE) {
261                 frontend::FontMetrics const & fm =
262                         theFontMetrics(cursor_.getFont());
263                 int const asc = fm.maxAscent();
264                 int const des = fm.maxDescent();
265                 Point const p = bv_funcs::getPos(*this, cursor_, cursor_.boundary());
266                 if (p.y_ - asc >= 0 && p.y_ + des < height_)
267                         return false;
268         }
269         center();
270         return true;
271 }
272
273
274 bool BufferView::multiParSel()
275 {
276         if (!cursor_.selection())
277                 return false;
278         bool ret = multiparsel_cache_;
279         multiparsel_cache_ = cursor_.selBegin().pit() != cursor_.selEnd().pit();
280         // Either this, or previous selection spans paragraphs
281         return ret || multiparsel_cache_;
282 }
283
284
285 bool BufferView::update(Update::flags flags)
286 {
287         // last_inset_ points to the last visited inset. This pointer may become
288         // invalid because of keyboard editing. Since all such operations
289         // causes screen update(), I reset last_inset_ to avoid such a problem.
290         last_inset_ = 0;
291         // This is close to a hot-path.
292         LYXERR(Debug::DEBUG)
293                 << BOOST_CURRENT_FUNCTION
294                 << "[fitcursor = " << (flags & Update::FitCursor)
295                 << ", forceupdate = " << (flags & Update::Force)
296                 << ", singlepar = " << (flags & Update::SinglePar)
297                 << "]  buffer: " << buffer_ << endl;
298
299         // Check needed to survive LyX startup
300         if (!buffer_)
301                 return false;
302
303         LYXERR(Debug::WORKAREA) << "BufferView::update" << std::endl;
304
305         // Update macro store
306         if (!(cursor().inMathed() && cursor().inMacroMode()))
307                 buffer_->buildMacros();
308
309         // Now do the first drawing step if needed. This consists on updating
310         // the CoordCache in updateMetrics().
311         // The second drawing step is done in WorkArea::redraw() if needed.
312
313         // Case when no explicit update is requested.
314         if (!flags) {
315                 // no need to redraw anything.
316                 metrics_info_.update_strategy = NoScreenUpdate;
317                 return false;
318         }
319
320         if (flags == Update::Decoration) {
321                 metrics_info_.update_strategy = DecorationUpdate;
322                 return true;
323         }
324
325         if (flags == Update::FitCursor
326                 || flags == (Update::Decoration | Update::FitCursor)) {
327                 bool const fit_cursor = fitCursor();
328                 // tell the frontend to update the screen if needed.
329                 if (fit_cursor) {
330                         updateMetrics(false);
331                         return true;
332                 }
333                 if (flags & Update::Decoration) {
334                         metrics_info_.update_strategy = DecorationUpdate;
335                         return true;
336                 }
337                 // no screen update is needed.
338                 metrics_info_.update_strategy = NoScreenUpdate;
339                 return false;
340         }
341
342         bool full_metrics = flags & Update::Force;
343         if (flags & Update::MultiParSel)
344                 full_metrics |= multiParSel();
345
346         bool const single_par = !full_metrics;
347         updateMetrics(single_par);
348
349         if (flags & Update::FitCursor && fitCursor())
350                 updateMetrics(false);
351
352         // tell the frontend to update the screen.
353         return true;
354 }
355
356
357 void BufferView::updateScrollbar()
358 {
359         if (!buffer_) {
360                 LYXERR(Debug::DEBUG) << BOOST_CURRENT_FUNCTION
361                                      << " no text in updateScrollbar" << endl;
362                 scrollbarParameters_.reset();
363                 return;
364         }
365
366         Text & t = buffer_->text();
367         TextMetrics & tm = text_metrics_[&t];
368
369         int const parsize = int(t.paragraphs().size() - 1);
370         if (anchor_ref_ >  parsize)  {
371                 anchor_ref_ = parsize;
372                 offset_ref_ = 0;
373         }
374
375         LYXERR(Debug::GUI)
376                 << BOOST_CURRENT_FUNCTION
377                 << " Updating scrollbar: height: " << t.paragraphs().size()
378                 << " curr par: " << cursor_.bottom().pit()
379                 << " default height " << defaultRowHeight() << endl;
380
381         // It would be better to fix the scrollbar to understand
382         // values in [0..1] and divide everything by wh
383
384         // estimated average paragraph height:
385         if (wh_ == 0)
386                 wh_ = height_ / 4;
387
388         int h = tm.parMetrics(anchor_ref_).height();
389
390         // Normalize anchor/offset (MV):
391         while (offset_ref_ > h && anchor_ref_ < parsize) {
392                 anchor_ref_++;
393                 offset_ref_ -= h;
394                 h = tm.parMetrics(anchor_ref_).height();
395         }
396         // Look at paragraph heights on-screen
397         int sumh = 0;
398         int nh = 0;
399         for (pit_type pit = anchor_ref_; pit <= parsize; ++pit) {
400                 if (sumh > height_)
401                         break;
402                 int const h2 = tm.parMetrics(pit).height();
403                 sumh += h2;
404                 nh++;
405         }
406
407         BOOST_ASSERT(nh);
408         int const hav = sumh / nh;
409         // More realistic average paragraph height
410         if (hav > wh_)
411                 wh_ = hav;
412
413         BOOST_ASSERT(h);
414         scrollbarParameters_.height = (parsize + 1) * wh_;
415         scrollbarParameters_.position = anchor_ref_ * wh_ + int(offset_ref_ * wh_ / float(h));
416         scrollbarParameters_.lineScrollHeight = int(wh_ * defaultRowHeight() / float(h));
417 }
418
419
420 ScrollbarParameters const & BufferView::scrollbarParameters() const
421 {
422         return scrollbarParameters_;
423 }
424
425
426 void BufferView::scrollDocView(int value)
427 {
428         LYXERR(Debug::GUI) << BOOST_CURRENT_FUNCTION
429                            << "[ value = " << value << "]" << endl;
430
431         if (!buffer_)
432                 return;
433
434         Text & t = buffer_->text();
435         TextMetrics & tm = text_metrics_[&t];
436
437         float const bar = value / float(wh_ * t.paragraphs().size());
438
439         anchor_ref_ = int(bar * t.paragraphs().size());
440         if (anchor_ref_ >  int(t.paragraphs().size()) - 1)
441                 anchor_ref_ = int(t.paragraphs().size()) - 1;
442
443         tm.redoParagraph(anchor_ref_);
444         int const h = tm.parMetrics(anchor_ref_).height();
445         offset_ref_ = int((bar * t.paragraphs().size() - anchor_ref_) * h);
446         updateMetrics(false);
447 }
448
449
450 void BufferView::setCursorFromScrollbar()
451 {
452         if (!buffer_)
453                 return;
454
455         Text & t = buffer_->text();
456
457         int const height = 2 * defaultRowHeight();
458         int const first = height;
459         int const last = height_ - height;
460         Cursor & cur = cursor_;
461
462         bv_funcs::CurStatus st = bv_funcs::status(this, cur);
463
464         switch (st) {
465         case bv_funcs::CUR_ABOVE:
466                 // We reset the cursor because bv_funcs::status() does not
467                 // work when the cursor is within mathed.
468                 cur.reset(buffer_->inset());
469                 t.setCursorFromCoordinates(cur, 0, first);
470                 cur.clearSelection();
471                 break;
472         case bv_funcs::CUR_BELOW:
473                 // We reset the cursor because bv_funcs::status() does not
474                 // work when the cursor is within mathed.
475                 cur.reset(buffer_->inset());
476                 t.setCursorFromCoordinates(cur, 0, last);
477                 cur.clearSelection();
478                 break;
479         case bv_funcs::CUR_INSIDE:
480                 int const y = bv_funcs::getPos(*this, cur, cur.boundary()).y_;
481                 int const newy = min(last, max(y, first));
482                 if (y != newy) {
483                         cur.reset(buffer_->inset());
484                         t.setCursorFromCoordinates(cur, 0, newy);
485                 }
486         }
487 }
488
489
490 Change const BufferView::getCurrentChange() const
491 {
492         if (!cursor_.selection())
493                 return Change(Change::UNCHANGED);
494
495         DocIterator dit = cursor_.selectionBegin();
496         return dit.paragraph().lookupChange(dit.pos());
497 }
498
499
500 void BufferView::saveBookmark(unsigned int idx)
501 {
502         // tenatively save bookmark, id and pos will be used to
503         // acturately locate a bookmark in a 'live' lyx session.
504         // pit and pos will be updated with bottom level pit/pos
505         // when lyx exits.
506         LyX::ref().session().bookmarks().save(
507                 FileName(buffer_->fileName()),
508                 cursor_.bottom().pit(),
509                 cursor_.bottom().pos(),
510                 cursor_.paragraph().id(),
511                 cursor_.pos(),
512                 idx
513         );
514         if (idx)
515                 // emit message signal.
516                 message(_("Save bookmark"));
517 }
518
519
520 boost::tuple<pit_type, pos_type, int> BufferView::moveToPosition(pit_type bottom_pit, pos_type bottom_pos,
521         int top_id, pos_type top_pos)
522 {
523         cursor_.clearSelection();
524
525         // if a valid par_id is given, try it first
526         // This is the case for a 'live' bookmark when unique paragraph ID
527         // is used to track bookmarks.
528         if (top_id > 0) {
529                 ParIterator par = buffer_->getParFromID(top_id);
530                 if (par != buffer_->par_iterator_end()) {
531                         DocIterator dit = makeDocIterator(par, min(par->size(), top_pos));
532                         // Some slices of the iterator may not be
533                         // reachable (e.g. closed collapsable inset)
534                         // so the dociterator may need to be
535                         // shortened. Otherwise, setCursor may crash
536                         // lyx when the cursor can not be set to these
537                         // insets.
538                         size_t const n = dit.depth();
539                         for (size_t i = 0; i < n; ++i)
540                                 if (dit[i].inset().editable() != Inset::HIGHLY_EDITABLE) {
541                                         dit.resize(i);
542                                         break;
543                                 }
544                         setCursor(dit);
545                         // Note: return bottom (document) level pit.
546                         return boost::make_tuple(cursor_.bottom().pit(), cursor_.bottom().pos(), top_id);
547                 }
548         }
549         // if top_id == 0, or searching through top_id failed
550         // This is the case for a 'restored' bookmark when only bottom
551         // (document level) pit was saved. Because of this, bookmark
552         // restoration is inaccurate. If a bookmark was within an inset,
553         // it will be restored to the left of the outmost inset that contains
554         // the bookmark.
555         if (static_cast<size_t>(bottom_pit) < buffer_->paragraphs().size()) {
556                 DocIterator it = doc_iterator_begin(buffer_->inset());
557                 it.pit() = bottom_pit;
558                 it.pos() = min(bottom_pos, it.paragraph().size());
559                 setCursor(it);
560                 return boost::make_tuple(it.pit(), it.pos(),
561                                          it.paragraph().id());
562         }
563         // both methods fail
564         return boost::make_tuple(pit_type(0), pos_type(0), 0);
565 }
566
567
568 void BufferView::translateAndInsert(char_type c, Text * t, Cursor & cur)
569 {
570         if (lyxrc.rtl_support) {
571                 if (cursor_.innerText()->real_current_font.isRightToLeft()) {
572                         if (intl_->keymap == Intl::PRIMARY)
573                                 intl_->keyMapSec();
574                 } else {
575                         if (intl_->keymap == Intl::SECONDARY)
576                                 intl_->keyMapPrim();
577                 }
578         }
579         
580         intl_->getTransManager().translateAndInsert(c, t, cur);
581 }
582
583
584 int BufferView::workWidth() const
585 {
586         return width_;
587 }
588
589
590 void BufferView::center()
591 {
592         CursorSlice & bot = cursor_.bottom();
593         TextMetrics & tm = text_metrics_[bot.text()];
594         pit_type const pit = bot.pit();
595         tm.redoParagraph(pit);
596         ParagraphMetrics const & pm = tm.parMetrics(pit);
597         anchor_ref_ = pit;
598         offset_ref_ = bv_funcs::coordOffset(*this, cursor_, cursor_.boundary()).y_
599                 + pm.ascent() - height_ / 2;
600 }
601
602
603 FuncStatus BufferView::getStatus(FuncRequest const & cmd)
604 {
605         FuncStatus flag;
606
607         Cursor & cur = cursor_;
608
609         switch (cmd.action) {
610
611         case LFUN_UNDO:
612                 flag.enabled(!buffer_->undostack().empty());
613                 break;
614         case LFUN_REDO:
615                 flag.enabled(!buffer_->redostack().empty());
616                 break;
617         case LFUN_FILE_INSERT:
618         case LFUN_FILE_INSERT_PLAINTEXT_PARA:
619         case LFUN_FILE_INSERT_PLAINTEXT:
620         case LFUN_BOOKMARK_SAVE:
621                 // FIXME: Actually, these LFUNS should be moved to Text
622                 flag.enabled(cur.inTexted());
623                 break;
624         case LFUN_FONT_STATE:
625         case LFUN_LABEL_INSERT:
626         case LFUN_PARAGRAPH_GOTO:
627         // FIXME handle non-trivially
628         case LFUN_OUTLINE_UP:
629         case LFUN_OUTLINE_DOWN:
630         case LFUN_OUTLINE_IN:
631         case LFUN_OUTLINE_OUT:
632         case LFUN_NOTE_NEXT:
633         case LFUN_REFERENCE_NEXT:
634         case LFUN_WORD_FIND:
635         case LFUN_MARK_OFF:
636         case LFUN_MARK_ON:
637         case LFUN_MARK_TOGGLE:
638         case LFUN_SCREEN_RECENTER:
639         case LFUN_BIBTEX_DATABASE_ADD:
640         case LFUN_BIBTEX_DATABASE_DEL:
641         case LFUN_WORDS_COUNT:
642         case LFUN_NEXT_INSET_TOGGLE:
643                 flag.enabled(true);
644                 break;
645
646         case LFUN_WORD_REPLACE:
647                 flag.enabled(!cur.paragraph().isDeleted(cur.pos()));
648                 break;
649
650         case LFUN_LABEL_GOTO: {
651                 flag.enabled(!cmd.argument().empty()
652                     || getInsetByCode<InsetRef>(cur, Inset::REF_CODE));
653                 break;
654         }
655
656         case LFUN_CHANGES_TRACK:
657                 flag.enabled(true);
658                 flag.setOnOff(buffer_->params().trackChanges);
659                 break;
660
661         case LFUN_CHANGES_OUTPUT:
662                 flag.enabled(buffer_);
663                 flag.setOnOff(buffer_->params().outputChanges);
664                 break;
665
666         case LFUN_CHANGES_MERGE:
667         case LFUN_CHANGE_NEXT:
668         case LFUN_ALL_CHANGES_ACCEPT:
669         case LFUN_ALL_CHANGES_REJECT:
670                 // TODO: context-sensitive enabling of LFUNs
671                 // In principle, these command should only be enabled if there
672                 // is a change in the document. However, without proper
673                 // optimizations, this will inevitably result in poor performance.
674                 flag.enabled(buffer_);
675                 break;
676
677         case LFUN_BUFFER_TOGGLE_COMPRESSION: {
678                 flag.setOnOff(buffer_->params().compressed);
679                 break;
680         }
681
682         default:
683                 flag.enabled(false);
684         }
685
686         return flag;
687 }
688
689
690 Update::flags BufferView::dispatch(FuncRequest const & cmd)
691 {
692         //lyxerr << BOOST_CURRENT_FUNCTION
693         //       << [ cmd = " << cmd << "]" << endl;
694
695         // Make sure that the cached BufferView is correct.
696         LYXERR(Debug::ACTION) << BOOST_CURRENT_FUNCTION
697                 << " action[" << cmd.action << ']'
698                 << " arg[" << to_utf8(cmd.argument()) << ']'
699                 << " x[" << cmd.x << ']'
700                 << " y[" << cmd.y << ']'
701                 << " button[" << cmd.button() << ']'
702                 << endl;
703
704         // FIXME: this should not be possible.
705         if (!buffer_)
706                 return Update::None;
707
708         Cursor & cur = cursor_;
709         // Default Update flags.
710         Update::flags updateFlags = Update::Force | Update::FitCursor;
711
712         switch (cmd.action) {
713
714         case LFUN_UNDO:
715                 cur.message(_("Undo"));
716                 cur.clearSelection();
717                 if (!textUndo(*this)) {
718                         cur.message(_("No further undo information"));
719                         updateFlags = Update::None;
720                 }
721                 break;
722
723         case LFUN_REDO:
724                 cur.message(_("Redo"));
725                 cur.clearSelection();
726                 if (!textRedo(*this)) {
727                         cur.message(_("No further redo information"));
728                         updateFlags = Update::None;
729                 }
730                 break;
731
732         case LFUN_FILE_INSERT:
733                 // FIXME UNICODE
734                 menuInsertLyXFile(to_utf8(cmd.argument()));
735                 break;
736
737         case LFUN_FILE_INSERT_PLAINTEXT_PARA:
738                 // FIXME UNICODE
739                 insertPlaintextFile(this, to_utf8(cmd.argument()), true);
740                 break;
741
742         case LFUN_FILE_INSERT_PLAINTEXT:
743                 // FIXME UNICODE
744                 insertPlaintextFile(this, to_utf8(cmd.argument()), false);
745                 break;
746
747         case LFUN_FONT_STATE:
748                 cur.message(cur.currentState());
749                 break;
750
751         case LFUN_BOOKMARK_SAVE:
752                 saveBookmark(convert<unsigned int>(to_utf8(cmd.argument())));
753                 break;
754
755         case LFUN_LABEL_GOTO: {
756                 docstring label = cmd.argument();
757                 if (label.empty()) {
758                         InsetRef * inset =
759                                 getInsetByCode<InsetRef>(cursor_,
760                                                          Inset::REF_CODE);
761                         if (inset) {
762                                 label = inset->getParam("reference");
763                                 // persistent=false: use temp_bookmark
764                                 saveBookmark(0);
765                         }
766                 }
767
768                 if (!label.empty())
769                         gotoLabel(label);
770                 break;
771         }
772
773         case LFUN_PARAGRAPH_GOTO: {
774                 int const id = convert<int>(to_utf8(cmd.argument()));
775                 int i = 0;
776                 for (Buffer * b = buffer_; i == 0 || b != buffer_; b = theBufferList().next(b)) {
777                         ParIterator par = b->getParFromID(id);
778                         if (par == b->par_iterator_end()) {
779                                 LYXERR(Debug::INFO)
780                                         << "No matching paragraph found! ["
781                                         << id << "]." << endl;
782                         } else {
783                                 LYXERR(Debug::INFO)
784                                         << "Paragraph " << par->id()
785                                         << " found in buffer `"
786                                         << b->fileName() << "'." << endl;
787
788                                 if (b == buffer_) {
789                                         // Set the cursor
790                                         setCursor(makeDocIterator(par, 0));
791                                 } else {
792                                         // Switch to other buffer view and resend cmd
793                                         theLyXFunc().dispatch(FuncRequest(
794                                                 LFUN_BUFFER_SWITCH, b->fileName()));
795                                         theLyXFunc().dispatch(cmd);
796                                         updateFlags = Update::None;
797                                 }
798                                 break;
799                         }
800                         ++i;
801                 }
802                 break;
803         }
804
805         case LFUN_OUTLINE_UP:
806                 toc::outline(toc::Up, cursor_);
807                 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
808                 updateLabels(*buffer_);
809                 break;
810         case LFUN_OUTLINE_DOWN:
811                 toc::outline(toc::Down, cursor_);
812                 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
813                 updateLabels(*buffer_);
814                 break;
815         case LFUN_OUTLINE_IN:
816                 toc::outline(toc::In, cursor_);
817                 updateLabels(*buffer_);
818                 break;
819         case LFUN_OUTLINE_OUT:
820                 toc::outline(toc::Out, cursor_);
821                 updateLabels(*buffer_);
822                 break;
823
824         case LFUN_NOTE_NEXT:
825                 bv_funcs::gotoInset(this, Inset::NOTE_CODE, false);
826                 break;
827
828         case LFUN_REFERENCE_NEXT: {
829                 vector<Inset_code> tmp;
830                 tmp.push_back(Inset::LABEL_CODE);
831                 tmp.push_back(Inset::REF_CODE);
832                 bv_funcs::gotoInset(this, tmp, true);
833                 break;
834         }
835
836         case LFUN_CHANGES_TRACK:
837                 buffer_->params().trackChanges = !buffer_->params().trackChanges;
838                 break;
839
840         case LFUN_CHANGES_OUTPUT:
841                 buffer_->params().outputChanges = !buffer_->params().outputChanges;
842                 if (buffer_->params().outputChanges) {
843                         bool dvipost    = LaTeXFeatures::isAvailable("dvipost");
844                         bool xcolorsoul = LaTeXFeatures::isAvailable("soul") &&
845                                           LaTeXFeatures::isAvailable("xcolor");
846
847                         if (!dvipost && !xcolorsoul) {
848                                 Alert::warning(_("Changes not shown in LaTeX output"),
849                                                _("Changes will not be highlighted in LaTeX output, "
850                                                  "because neither dvipost nor xcolor/soul are installed.\n"
851                                                  "Please install these packages or redefine "
852                                                  "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
853                         } else if (!xcolorsoul) {
854                                 Alert::warning(_("Changes not shown in LaTeX output"),
855                                                _("Changes will not be highlighted in LaTeX output "
856                                                  "when using pdflatex, because xcolor and soul are not installed.\n"
857                                                  "Please install both packages or redefine "
858                                                  "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
859                         }
860                 }
861                 break;
862
863         case LFUN_CHANGE_NEXT:
864                 findNextChange(this);
865                 break;
866
867         case LFUN_CHANGES_MERGE:
868                 if (findNextChange(this))
869                         showDialog("changes");
870                 break;
871
872         case LFUN_ALL_CHANGES_ACCEPT:
873                 // select complete document
874                 cursor_.reset(buffer_->inset());
875                 cursor_.selHandle(true);
876                 buffer_->text().cursorBottom(cursor_);
877                 // accept everything in a single step to support atomic undo
878                 buffer_->text().acceptOrRejectChanges(cursor_, Text::ACCEPT);
879                 break;
880
881         case LFUN_ALL_CHANGES_REJECT:
882                 // select complete document
883                 cursor_.reset(buffer_->inset());
884                 cursor_.selHandle(true);
885                 buffer_->text().cursorBottom(cursor_);
886                 // reject everything in a single step to support atomic undo
887                 // Note: reject does not work recursively; the user may have to repeat the operation
888                 buffer_->text().acceptOrRejectChanges(cursor_, Text::REJECT);
889                 break;
890
891         case LFUN_WORD_FIND:
892                 find(this, cmd);
893                 break;
894
895         case LFUN_WORD_REPLACE:
896                 replace(this, cmd);
897                 break;
898
899         case LFUN_MARK_OFF:
900                 cur.clearSelection();
901                 cur.resetAnchor();
902                 cur.message(from_utf8(N_("Mark off")));
903                 break;
904
905         case LFUN_MARK_ON:
906                 cur.clearSelection();
907                 cur.mark() = true;
908                 cur.resetAnchor();
909                 cur.message(from_utf8(N_("Mark on")));
910                 break;
911
912         case LFUN_MARK_TOGGLE:
913                 cur.clearSelection();
914                 if (cur.mark()) {
915                         cur.mark() = false;
916                         cur.message(from_utf8(N_("Mark removed")));
917                 } else {
918                         cur.mark() = true;
919                         cur.message(from_utf8(N_("Mark set")));
920                 }
921                 cur.resetAnchor();
922                 break;
923
924         case LFUN_SCREEN_RECENTER:
925                 center();
926                 break;
927
928         case LFUN_BIBTEX_DATABASE_ADD: {
929                 Cursor tmpcur = cursor_;
930                 bv_funcs::findInset(tmpcur, Inset::BIBTEX_CODE, false);
931                 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
932                                                 Inset::BIBTEX_CODE);
933                 if (inset) {
934                         if (inset->addDatabase(to_utf8(cmd.argument())))
935                                 buffer_->updateBibfilesCache();
936                 }
937                 break;
938         }
939
940         case LFUN_BIBTEX_DATABASE_DEL: {
941                 Cursor tmpcur = cursor_;
942                 bv_funcs::findInset(tmpcur, Inset::BIBTEX_CODE, false);
943                 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
944                                                 Inset::BIBTEX_CODE);
945                 if (inset) {
946                         if (inset->delDatabase(to_utf8(cmd.argument())))
947                                 buffer_->updateBibfilesCache();
948                 }
949                 break;
950         }
951
952         case LFUN_WORDS_COUNT: {
953                 DocIterator from, to;
954                 if (cur.selection()) {
955                         from = cur.selectionBegin();
956                         to = cur.selectionEnd();
957                 } else {
958                         from = doc_iterator_begin(buffer_->inset());
959                         to = doc_iterator_end(buffer_->inset());
960                 }
961                 int const count = countWords(from, to);
962                 docstring message;
963                 if (count != 1) {
964                         if (cur.selection())
965                                 message = bformat(_("%1$d words in selection."),
966                                           count);
967                                 else
968                                         message = bformat(_("%1$d words in document."),
969                                                           count);
970                 }
971                 else {
972                         if (cur.selection())
973                                 message = _("One word in selection.");
974                         else
975                                 message = _("One word in document.");
976                 }
977
978                 Alert::information(_("Count words"), message);
979         }
980                 break;
981
982         case LFUN_BUFFER_TOGGLE_COMPRESSION:
983                 // turn compression on/off
984                 buffer_->params().compressed = !buffer_->params().compressed;
985                 break;
986
987         case LFUN_NEXT_INSET_TOGGLE: {
988                 // this is the real function we want to invoke
989                 FuncRequest tmpcmd = FuncRequest(LFUN_INSET_TOGGLE, cmd.origin);
990                 // if there is an inset at cursor, see whether it
991                 // wants to toggle.
992                 Inset * inset = cur.nextInset();
993                 if (inset && inset->isActive()) {
994                         Cursor tmpcur = cur;
995                         tmpcur.pushLeft(*inset);
996                         inset->dispatch(tmpcur, tmpcmd);
997                         if (tmpcur.result().dispatched()) {
998                                 cur.dispatched();
999                         }
1000                 }
1001                 // if it did not work, try the underlying inset.
1002                 if (!cur.result().dispatched())
1003                         cur.dispatch(tmpcmd);
1004
1005                 if (cur.result().dispatched())
1006                         cur.clearSelection();
1007
1008                 break;
1009         }
1010
1011         default:
1012                 updateFlags = Update::None;
1013         }
1014
1015         return updateFlags;
1016 }
1017
1018
1019 docstring const BufferView::requestSelection()
1020 {
1021         if (!buffer_)
1022                 return docstring();
1023
1024         Cursor & cur = cursor_;
1025
1026         if (!cur.selection()) {
1027                 xsel_cache_.set = false;
1028                 return docstring();
1029         }
1030
1031         if (!xsel_cache_.set ||
1032             cur.top() != xsel_cache_.cursor ||
1033             cur.anchor_.top() != xsel_cache_.anchor)
1034         {
1035                 xsel_cache_.cursor = cur.top();
1036                 xsel_cache_.anchor = cur.anchor_.top();
1037                 xsel_cache_.set = cur.selection();
1038                 return cur.selectionAsString(false);
1039         }
1040         return docstring();
1041 }
1042
1043
1044 void BufferView::clearSelection()
1045 {
1046         if (buffer_) {
1047                 cursor_.clearSelection();
1048                 // Clear the selection buffer. Otherwise a subsequent
1049                 // middle-mouse-button paste would use the selection buffer,
1050                 // not the more current external selection.
1051                 cap::clearSelection();
1052                 xsel_cache_.set = false;
1053                 // The buffer did not really change, but this causes the
1054                 // redraw we need because we cleared the selection above.
1055                 buffer_->changed();
1056         }
1057 }
1058
1059
1060 void BufferView::workAreaResize(int width, int height)
1061 {
1062         // Update from work area
1063         width_ = width;
1064         height_ = height;
1065
1066         // The complete text metrics will be redone.
1067         text_metrics_.clear();
1068
1069         if (buffer_)
1070                 resize();
1071 }
1072
1073
1074 Inset const * BufferView::getCoveringInset(Text const & text, int x, int y)
1075 {
1076         pit_type pit = text.getPitNearY(*this, y);
1077         BOOST_ASSERT(pit != -1);
1078         Paragraph const & par = text.getPar(pit);
1079
1080         LYXERR(Debug::DEBUG)
1081                 << BOOST_CURRENT_FUNCTION
1082                 << ": x: " << x
1083                 << " y: " << y
1084                 << "  pit: " << pit
1085                 << endl;
1086         InsetList::const_iterator iit = par.insetlist.begin();
1087         InsetList::const_iterator iend = par.insetlist.end();
1088         for (; iit != iend; ++iit) {
1089                 Inset * const inset = iit->inset;
1090                 if (inset->covers(*this, x, y)) {
1091                         if (!inset->descendable())
1092                                 // No need to go further down if the inset is not
1093                                 // descendable.
1094                                 return inset;
1095
1096                         size_t cell_number = inset->nargs();
1097                         // Check all the inner cell.
1098                         for (size_t i = 0; i != cell_number; ++i) {
1099                                 Text const * inner_text = inset->getText(i);
1100                                 if (inner_text) {
1101                                         // Try deeper.
1102                                         Inset const * inset_deeper =
1103                                                 getCoveringInset(*inner_text, x, y);
1104                                         if (inset_deeper)
1105                                                 return inset_deeper;
1106                                 }
1107                         }
1108
1109                         LYXERR(Debug::DEBUG)
1110                                 << BOOST_CURRENT_FUNCTION
1111                                 << ": Hit inset: " << inset << endl;
1112                         return inset;
1113                 }
1114         }
1115         LYXERR(Debug::DEBUG)
1116                 << BOOST_CURRENT_FUNCTION
1117                 << ": No inset hit. " << endl;
1118         return 0;
1119 }
1120
1121
1122 bool BufferView::workAreaDispatch(FuncRequest const & cmd0)
1123 {
1124         //lyxerr << BOOST_CURRENT_FUNCTION << "[ cmd0 " << cmd0 << "]" << endl;
1125
1126         // This is only called for mouse related events including
1127         // LFUN_FILE_OPEN generated by drag-and-drop.
1128         FuncRequest cmd = cmd0;
1129
1130         // E.g. Qt mouse press when no buffer
1131         if (!buffer_)
1132                 return false;
1133
1134         Cursor cur(*this);
1135         cur.push(buffer_->inset());
1136         cur.selection() = cursor_.selection();
1137
1138         // Either the inset under the cursor or the
1139         // surrounding Text will handle this event.
1140
1141         // make sure we stay within the screen...
1142         cmd.y = min(max(cmd.y, -1), height_);
1143
1144         if (cmd.action == LFUN_MOUSE_MOTION && cmd.button() == mouse_button::none) {
1145
1146                 // Get inset under mouse, if there is one.
1147                 Inset const * covering_inset =
1148                         getCoveringInset(buffer_->text(), cmd.x, cmd.y);
1149                 if (covering_inset == last_inset_)
1150                         // Same inset, no need to do anything...
1151                         return false;
1152
1153                 bool need_redraw = false;
1154                 // const_cast because of setMouseHover().
1155                 Inset * inset = const_cast<Inset *>(covering_inset);
1156                 if (last_inset_)
1157                         // Remove the hint on the last hovered inset (if any).
1158                         need_redraw |= last_inset_->setMouseHover(false);
1159                 if (inset)
1160                         // Highlighted the newly hovered inset (if any).
1161                         need_redraw |= inset->setMouseHover(true);
1162                 last_inset_ = inset;
1163
1164                 // if last metrics update was in singlepar mode, WorkArea::redraw() will
1165                 // not expose the button for redraw. We adjust here the metrics dimension
1166                 // to enable a full redraw.
1167                 // FIXME: It is possible to redraw only the area around the button!
1168                 if (need_redraw
1169                         && metrics_info_.update_strategy == SingleParUpdate) {
1170                         // FIXME: It should be possible to redraw only the area around
1171                         // the button by doing this:
1172                         //
1173                         //metrics_info_.singlepar = false;
1174                         //metrics_info_.y1 = ymin of button;
1175                         //metrics_info_.y2 = ymax of button;
1176                         //
1177                         // Unfortunately, rowpainter.cpp:paintText() does not distinguish
1178                         // between background updates and text updates. So we use the hammer
1179                         // solution for now. We could also avoid the updateMetrics() below
1180                         // by using the first and last pit of the CoordCache. Have a look
1181                         // at Text::getPitNearY() to see what I mean.
1182                         //
1183                         //metrics_info_.pit1 = first pit of CoordCache;
1184                         //metrics_info_.pit2 = last pit of CoordCache;
1185                         //metrics_info_.singlepar = false;
1186                         //metrics_info_.y1 = 0;
1187                         //metrics_info_.y2 = height_;
1188                         //
1189                         updateMetrics(false);
1190                 }
1191
1192                 // This event (moving without mouse click) is not passed further.
1193                 // This should be changed if it is further utilized.
1194                 return need_redraw;
1195         }
1196
1197         // Build temporary cursor.
1198         Inset * inset = buffer_->text().editXY(cur, cmd.x, cmd.y);
1199
1200         // Put anchor at the same position.
1201         cur.resetAnchor();
1202
1203         // Try to dispatch to an non-editable inset near this position
1204         // via the temp cursor. If the inset wishes to change the real
1205         // cursor it has to do so explicitly by using
1206         //  cur.bv().cursor() = cur;  (or similar)
1207         if (inset) {
1208                 inset->dispatch(cur, cmd);
1209         }
1210
1211         // Now dispatch to the temporary cursor. If the real cursor should
1212         // be modified, the inset's dispatch has to do so explicitly.
1213         if (!cur.result().dispatched())
1214                 cur.dispatch(cmd);
1215
1216         // Redraw if requested and necessary.
1217         if (cur.result().dispatched() && cur.result().update())
1218                 return update(cur.result().update());
1219
1220         return false;
1221 }
1222
1223
1224 void BufferView::scroll(int /*lines*/)
1225 {
1226 //      if (!buffer_)
1227 //              return;
1228 //
1229 //      Text const * t = &buffer_->text();
1230 //      int const line_height = defaultRowHeight();
1231 //
1232 //      // The new absolute coordinate
1233 //      int new_top_y = top_y() + lines * line_height;
1234 //
1235 //      // Restrict to a valid value
1236 //      new_top_y = std::min(t->height() - 4 * line_height, new_top_y);
1237 //      new_top_y = std::max(0, new_top_y);
1238 //
1239 //      scrollDocView(new_top_y);
1240 //
1241 }
1242
1243
1244 void BufferView::setCursorFromRow(int row)
1245 {
1246         int tmpid = -1;
1247         int tmppos = -1;
1248
1249         buffer_->texrow().getIdFromRow(row, tmpid, tmppos);
1250
1251         if (tmpid == -1)
1252                 buffer_->text().setCursor(cursor_, 0, 0);
1253         else
1254                 buffer_->text().setCursor(cursor_, buffer_->getParFromID(tmpid).pit(), tmppos);
1255 }
1256
1257
1258 void BufferView::gotoLabel(docstring const & label)
1259 {
1260         for (InsetIterator it = inset_iterator_begin(buffer_->inset()); it; ++it) {
1261                 vector<docstring> labels;
1262                 it->getLabelList(*buffer_, labels);
1263                 if (std::find(labels.begin(), labels.end(), label) != labels.end()) {
1264                         setCursor(it);
1265                         update();
1266                         return;
1267                 }
1268         }
1269 }
1270
1271
1272 TextMetrics const & BufferView::textMetrics(Text const * t) const
1273 {
1274         return const_cast<BufferView *>(this)->textMetrics(t);
1275 }
1276
1277
1278 TextMetrics & BufferView::textMetrics(Text const * t)
1279 {
1280         TextMetricsCache::iterator tmc_it  = text_metrics_.find(t);
1281         if (tmc_it == text_metrics_.end()) {
1282                 tmc_it = text_metrics_.insert(
1283                         make_pair(t, TextMetrics(this, const_cast<Text *>(t)))).first;
1284         }
1285         return tmc_it->second;
1286 }
1287
1288
1289 ParagraphMetrics const & BufferView::parMetrics(Text const * t,
1290                 pit_type pit) const
1291 {
1292         return textMetrics(t).parMetrics(pit);
1293 }
1294
1295
1296 int BufferView::workHeight() const
1297 {
1298         return height_;
1299 }
1300
1301
1302 void BufferView::setCursor(DocIterator const & dit)
1303 {
1304         size_t const n = dit.depth();
1305         for (size_t i = 0; i < n; ++i)
1306                 dit[i].inset().edit(cursor_, true);
1307
1308         cursor_.setCursor(dit);
1309         cursor_.selection() = false;
1310 }
1311
1312
1313 bool BufferView::checkDepm(Cursor & cur, Cursor & old)
1314 {
1315         // Would be wrong to delete anything if we have a selection.
1316         if (cur.selection())
1317                 return false;
1318
1319         bool need_anchor_change = false;
1320         bool changed = cursor_.text()->deleteEmptyParagraphMechanism(cur, old,
1321                 need_anchor_change);
1322
1323         if (need_anchor_change)
1324                 cur.resetAnchor();
1325
1326         if (!changed)
1327                 return false;
1328
1329         updateLabels(*buffer_);
1330
1331         updateMetrics(false);
1332         buffer_->changed();
1333         return true;
1334 }
1335
1336
1337 bool BufferView::mouseSetCursor(Cursor & cur)
1338 {
1339         BOOST_ASSERT(&cur.bv() == this);
1340
1341         // Has the cursor just left the inset?
1342         bool badcursor = false;
1343         bool leftinset = (&cursor_.inset() != &cur.inset());
1344         if (leftinset)
1345                 badcursor = cursor_.inset().notifyCursorLeaves(cursor_);
1346
1347         // do the dEPM magic if needed
1348         // FIXME: (1) move this to InsetText::notifyCursorLeaves?
1349         // FIXME: (2) if we had a working InsetText::notifyCursorLeaves,
1350         // the leftinset bool would not be necessary (badcursor instead).
1351         bool update = leftinset;
1352         if (!badcursor && cursor_.inTexted())
1353                 update |= checkDepm(cur, cursor_);
1354
1355         // if the cursor was in an empty script inset and the new
1356         // position is in the nucleus of the inset, notifyCursorLeaves
1357         // will kill the script inset itself. So we check all the
1358         // elements of the cursor to make sure that they are correct.
1359         // For an example, see bug 2933:
1360         // http://bugzilla.lyx.org/show_bug.cgi?id=2933
1361         // The code below could maybe be moved to a DocIterator method.
1362         //lyxerr << "cur before " << cur <<std::endl;
1363         DocIterator dit(cur.inset());
1364         dit.push_back(cur.bottom());
1365         size_t i = 1;
1366         while (i < cur.depth() && dit.nextInset() == &cur[i].inset()) {
1367                 dit.push_back(cur[i]);
1368                 ++i;
1369         }
1370         //lyxerr << "5 cur after" << dit <<std::endl;
1371
1372         cursor_.setCursor(dit);
1373         cursor_.boundary(cur.boundary());
1374         cursor_.clearSelection();
1375         finishUndo();
1376         return update;
1377 }
1378
1379
1380 void BufferView::putSelectionAt(DocIterator const & cur,
1381                                 int length, bool backwards)
1382 {
1383         cursor_.clearSelection();
1384
1385         setCursor(cur);
1386
1387         if (length) {
1388                 if (backwards) {
1389                         cursor_.pos() += length;
1390                         cursor_.setSelection(cursor_, -length);
1391                 } else
1392                         cursor_.setSelection(cursor_, length);
1393                 cap::saveSelection(cursor_);
1394         }
1395 }
1396
1397
1398 Cursor & BufferView::cursor()
1399 {
1400         return cursor_;
1401 }
1402
1403
1404 Cursor const & BufferView::cursor() const
1405 {
1406         return cursor_;
1407 }
1408
1409
1410 pit_type BufferView::anchor_ref() const
1411 {
1412         return anchor_ref_;
1413 }
1414
1415
1416 ViewMetricsInfo const & BufferView::viewMetricsInfo()
1417 {
1418         return metrics_info_;
1419 }
1420
1421
1422 // FIXME: We should split-up updateMetrics() for the singlepar case.
1423 void BufferView::updateMetrics(bool singlepar)
1424 {
1425         Text & buftext = buffer_->text();
1426         TextMetrics & tm = textMetrics(&buftext);
1427         pit_type size = int(buftext.paragraphs().size());
1428
1429         if (anchor_ref_ > int(buftext.paragraphs().size() - 1)) {
1430                 anchor_ref_ = int(buftext.paragraphs().size() - 1);
1431                 offset_ref_ = 0;
1432         }
1433
1434         // If the paragraph metrics has changed, we can not
1435         // use the singlepar optimisation.
1436         if (singlepar
1437                 // In Single Paragraph mode, rebreak only
1438                 // the (main text, not inset!) paragraph containing the cursor.
1439                 // (if this paragraph contains insets etc., rebreaking will
1440                 // recursively descend)
1441                 && tm.redoParagraph(cursor_.bottom().pit()))
1442                 singlepar = false;
1443
1444         pit_type const pit = anchor_ref_;
1445         int pit1 = pit;
1446         int pit2 = pit;
1447         size_t const npit = buftext.paragraphs().size();
1448
1449         // Rebreak anchor paragraph.
1450         if (!singlepar)
1451                 tm.redoParagraph(pit);
1452
1453         // Clear out the position cache in case of full screen redraw.
1454         if (!singlepar)
1455                 coord_cache_.clear();
1456
1457         int y0 = tm.parMetrics(pit).ascent() - offset_ref_;
1458
1459         // Redo paragraphs above anchor if necessary.
1460         int y1 = y0;
1461         while (y1 > 0 && pit1 > 0) {
1462                 y1 -= tm.parMetrics(pit1).ascent();
1463                 --pit1;
1464                 if (!singlepar)
1465                         tm.redoParagraph(pit1);
1466                 y1 -= tm.parMetrics(pit1).descent();
1467         }
1468
1469
1470         // Take care of ascent of first line
1471         y1 -= tm.parMetrics(pit1).ascent();
1472
1473         // Normalize anchor for next time
1474         anchor_ref_ = pit1;
1475         offset_ref_ = -y1;
1476
1477         // Grey at the beginning is ugly
1478         if (pit1 == 0 && y1 > 0) {
1479                 y0 -= y1;
1480                 y1 = 0;
1481                 anchor_ref_ = 0;
1482         }
1483
1484         // Redo paragraphs below the anchor if necessary.
1485         int y2 = y0;
1486         while (y2 < height_ && pit2 < int(npit) - 1) {
1487                 y2 += tm.parMetrics(pit2).descent();
1488                 ++pit2;
1489                 if (!singlepar)
1490                         tm.redoParagraph(pit2);
1491                 y2 += tm.parMetrics(pit2).ascent();
1492         }
1493
1494         // Take care of descent of last line
1495         y2 += tm.parMetrics(pit2).descent();
1496
1497         // The coordinates of all these paragraphs are correct, cache them
1498         int y = y1;
1499         CoordCache::InnerParPosCache & parPos = coord_cache_.parPos()[&buftext];
1500         for (pit_type pit = pit1; pit <= pit2; ++pit) {
1501                 ParagraphMetrics const & pm = tm.parMetrics(pit);
1502                 y += pm.ascent();
1503                 parPos[pit] = Point(0, y);
1504                 if (singlepar && pit == cursor_.bottom().pit()) {
1505                         // In Single Paragraph mode, collect here the
1506                         // y1 and y2 of the (one) paragraph the cursor is in
1507                         y1 = y - pm.ascent();
1508                         y2 = y + pm.descent();
1509                 }
1510                 y += pm.descent();
1511         }
1512
1513         if (singlepar) {
1514                 // collect cursor paragraph iter bounds
1515                 pit1 = cursor_.bottom().pit();
1516                 pit2 = cursor_.bottom().pit();
1517         }
1518
1519         LYXERR(Debug::DEBUG)
1520                 << BOOST_CURRENT_FUNCTION
1521                 << " y1: " << y1
1522                 << " y2: " << y2
1523                 << " pit1: " << pit1
1524                 << " pit2: " << pit2
1525                 << " npit: " << npit
1526                 << " singlepar: " << singlepar
1527                 << "size: " << size
1528                 << endl;
1529
1530         metrics_info_ = ViewMetricsInfo(pit1, pit2, y1, y2,
1531                 singlepar? SingleParUpdate: FullScreenUpdate, size);
1532
1533         if (lyxerr.debugging(Debug::WORKAREA)) {
1534                 LYXERR(Debug::WORKAREA) << "BufferView::updateMetrics" << endl;
1535                 coord_cache_.dump();
1536         }
1537 }
1538
1539
1540 void BufferView::menuInsertLyXFile(string const & filenm)
1541 {
1542         BOOST_ASSERT(cursor_.inTexted());
1543         string filename = filenm;
1544
1545         if (filename.empty()) {
1546                 // Launch a file browser
1547                 // FIXME UNICODE
1548                 string initpath = lyxrc.document_path;
1549
1550                 if (buffer_) {
1551                         string const trypath = buffer_->filePath();
1552                         // If directory is writeable, use this as default.
1553                         if (isDirWriteable(FileName(trypath)))
1554                                 initpath = trypath;
1555                 }
1556
1557                 // FIXME UNICODE
1558                 FileDialog fileDlg(_("Select LyX document to insert"),
1559                         LFUN_FILE_INSERT,
1560                         make_pair(_("Documents|#o#O"), from_utf8(lyxrc.document_path)),
1561                         make_pair(_("Examples|#E#e"),
1562                                     from_utf8(addPath(package().system_support().absFilename(),
1563                                     "examples"))));
1564
1565                 FileDialog::Result result =
1566                         fileDlg.open(from_utf8(initpath),
1567                                      FileFilterList(_("LyX Documents (*.lyx)")),
1568                                      docstring());
1569
1570                 if (result.first == FileDialog::Later)
1571                         return;
1572
1573                 // FIXME UNICODE
1574                 filename = to_utf8(result.second);
1575
1576                 // check selected filename
1577                 if (filename.empty()) {
1578                         // emit message signal.
1579                         message(_("Canceled."));
1580                         return;
1581                 }
1582         }
1583
1584         // Get absolute path of file and add ".lyx"
1585         // to the filename if necessary
1586         filename = fileSearch(string(), filename, "lyx").absFilename();
1587
1588         docstring const disp_fn = makeDisplayPath(filename);
1589         // emit message signal.
1590         message(bformat(_("Inserting document %1$s..."), disp_fn));
1591
1592         docstring res;
1593         Buffer buf("", false);
1594         if (lyx::loadLyXFile(&buf, FileName(filename))) {
1595                 ErrorList & el = buffer_->errorList("Parse");
1596                 // Copy the inserted document error list into the current buffer one.
1597                 el = buf.errorList("Parse");
1598                 recordUndo(cursor_);
1599                 cap::pasteParagraphList(cursor_, buf.paragraphs(),
1600                                              buf.params().textclass, el);
1601                 res = _("Document %1$s inserted.");
1602         } else
1603                 res = _("Could not insert document %1$s");
1604
1605         // emit message signal.
1606         message(bformat(res, disp_fn));
1607         buffer_->errors("Parse");
1608         resize();
1609 }
1610
1611 } // namespace lyx