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