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