3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Alfredo Braunstein
7 * \author Lars Gullik Bjønnes
10 * \author Jürgen Vigna
12 * Full author contact details are available in file CREDITS.
17 #include "BufferView.h"
20 #include "buffer_funcs.h"
21 #include "bufferlist.h"
22 #include "bufferparams.h"
23 #include "coordcache.h"
24 #include "CutAndPaste.h"
26 #include "dispatchresult.h"
27 #include "errorlist.h"
29 #include "FloatList.h"
30 #include "funcrequest.h"
31 #include "FuncStatus.h"
34 #include "insetiterator.h"
36 #include "LaTeXFeatures.h"
37 #include "lyx_cb.h" // added for Dispatch functions
41 #include "lyxlayout.h"
43 #include "lyxtextclass.h"
46 #include "paragraph.h"
47 #include "paragraph_funcs.h"
48 #include "ParagraphParameters.h"
49 #include "pariterator.h"
54 #include "WordLangTuple.h"
55 #include "metricsinfo.h"
57 #include "insets/insetbibtex.h"
58 #include "insets/insetcommand.h" // ChangeRefs
59 #include "insets/insetref.h"
60 #include "insets/insettext.h"
62 #include "frontends/Alert.h"
63 #include "frontends/FileDialog.h"
64 #include "frontends/FontMetrics.h"
66 #include "graphics/Previews.h"
68 #include "support/convert.h"
69 #include "support/filefilterlist.h"
70 #include "support/filetools.h"
71 #include "support/package.h"
72 #include "support/types.h"
74 #include <boost/bind.hpp>
75 #include <boost/current_function.hpp>
83 using support::addPath;
84 using support::bformat;
85 using support::FileFilterList;
86 using support::fileSearch;
87 using support::isDirWriteable;
88 using support::makeDisplayPath;
89 using support::makeAbsPath;
90 using support::package;
94 using std::istringstream;
98 using std::mem_fun_ref;
102 namespace Alert = frontend::Alert;
106 /// Return an inset of this class if it exists at the current cursor position
108 T * getInsetByCode(LCursor & cur, InsetBase::Code code)
111 DocIterator it = cur;
112 if (it.nextInset() &&
113 it.nextInset()->lyxCode() == code) {
114 inset = static_cast<T*>(it.nextInset());
122 BufferView::BufferView()
123 : width_(0), height_(0), buffer_(0), wh_(0),
125 multiparsel_cache_(false), anchor_ref_(0), offset_ref_(0),
128 xsel_cache_.set = false;
129 intl_->initKeyMapper(lyxrc.use_kbmap);
133 BufferView::~BufferView()
138 Buffer * BufferView::buffer() const
144 void BufferView::setBuffer(Buffer * b)
146 lyxerr[Debug::INFO] << BOOST_CURRENT_FUNCTION
147 << "[ b = " << b << "]" << endl;
150 // Save the actual cursor position and anchor inside the
151 // buffer so that it can be restored in case we rechange
152 // to this buffer later on.
153 buffer_->saveCursor(cursor_.selectionBegin(),
154 cursor_.selectionEnd());
155 // current buffer is going to be switched-off, save cursor pos
156 LyX::ref().session().lastFilePos().save(buffer_->fileName(),
157 boost::tie(cursor_.pit(), cursor_.pos()) );
160 // If we're quitting lyx, don't bother updating stuff
166 // If we are closing current buffer, switch to the first in
169 lyxerr[Debug::INFO] << BOOST_CURRENT_FUNCTION
170 << " No Buffer!" << endl;
171 // We are closing the buffer, use the first buffer as current
172 buffer_ = theBufferList().first();
174 // Set current buffer
179 cursor_ = LCursor(*this);
184 lyxerr[Debug::INFO] << BOOST_CURRENT_FUNCTION
185 << "Buffer addr: " << buffer_ << endl;
186 cursor_.push(buffer_->inset());
187 cursor_.resetAnchor();
188 buffer_->text().init(this);
189 buffer_->text().setCurrentFont(cursor_);
190 if (buffer_->getCursor().size() > 0 &&
191 buffer_->getAnchor().size() > 0)
193 cursor_.setCursor(buffer_->getAnchor().asDocIterator(&(buffer_->inset())));
194 cursor_.resetAnchor();
195 cursor_.setCursor(buffer_->getCursor().asDocIterator(&(buffer_->inset())));
196 cursor_.setSelection();
202 if (buffer_ && graphics::Previews::status() != LyXRC::PREVIEW_OFF)
203 graphics::Previews::get().generateBufferPreviews(*buffer_);
207 bool BufferView::loadLyXFile(string const & filename, bool tolastfiles)
209 // Get absolute path of file and add ".lyx"
210 // to the filename if necessary
211 string s = fileSearch(string(), filename, "lyx");
213 bool const found = !s.empty();
218 // File already open?
219 if (theBufferList().exists(s)) {
220 docstring const file = makeDisplayPath(s, 20);
221 docstring text = bformat(_("The document %1$s is already "
222 "loaded.\n\nDo you want to revert "
223 "to the saved version?"), file);
224 int const ret = Alert::prompt(_("Revert to saved document?"),
225 text, 0, 1, _("&Revert"), _("&Switch to document"));
228 setBuffer(theBufferList().getBuffer(s));
231 // FIXME: should be LFUN_REVERT
232 if (!theBufferList().close(theBufferList().getBuffer(s), false))
234 // Fall through to new load. (Asger)
241 b = theBufferList().newBuffer(s);
242 if (!lyx::loadLyXFile(b, s)) {
243 theBufferList().release(b);
247 docstring text = bformat(_("The document %1$s does not yet "
248 "exist.\n\nDo you want to create "
249 "a new document?"), from_utf8(s));
250 int const ret = Alert::prompt(_("Create new document?"),
251 text, 0, 1, _("&Create"), _("Cancel"));
254 b = newFile(s, string(), true);
262 // Send the "errors" signal in case of parsing errors
265 // scroll to the position when the file was last closed
266 if (lyxrc.use_lastfilepos) {
269 boost::tie(pit, pos) = LyX::ref().session().lastFilePos().load(s);
270 // I am not sure how to separate the following part to a function
271 // so I will leave this to Lars.
273 // check pit since the document may be externally changed.
274 if ( static_cast<size_t>(pit) < b->paragraphs().size() ) {
275 ParIterator it = b->par_iterator_begin();
276 ParIterator const end = b->par_iterator_end();
277 for (; it != end; ++it)
278 if (it.pit() == pit) {
279 // restored pos may be bigger than it->size
280 setCursor(makeDocIterator(it, min(pos, it->size())));
281 update(Update::FitCursor);
288 LyX::ref().session().lastFiles().add(b->fileName());
294 void BufferView::reload()
296 string const fn = buffer_->fileName();
297 if (theBufferList().close(buffer_, false))
302 void BufferView::resize()
307 lyxerr[Debug::DEBUG] << BOOST_CURRENT_FUNCTION << endl;
309 buffer_->text().init(this);
315 bool BufferView::fitCursor()
317 if (bv_funcs::status(this, cursor_) == bv_funcs::CUR_INSIDE) {
318 frontend::FontMetrics const & fm =
319 theFontMetrics(cursor_.getFont());
320 int const asc = fm.maxAscent();
321 int const des = fm.maxDescent();
322 Point const p = bv_funcs::getPos(*this, cursor_, cursor_.boundary());
323 if (p.y_ - asc >= 0 && p.y_ + des < height_)
331 bool BufferView::multiParSel()
333 if (!cursor_.selection())
335 bool ret = multiparsel_cache_;
336 multiparsel_cache_ = cursor_.selBegin().pit() != cursor_.selEnd().pit();
337 // Either this, or previous selection spans paragraphs
338 return ret || multiparsel_cache_;
342 bool BufferView::update(Update::flags flags)
344 // This is close to a hot-path.
345 if (lyxerr.debugging(Debug::DEBUG)) {
347 << BOOST_CURRENT_FUNCTION
348 << "[fitcursor = " << (flags & Update::FitCursor)
349 << ", forceupdate = " << (flags & Update::Force)
350 << ", singlepar = " << (flags & Update::SinglePar)
351 << "] buffer: " << buffer_ << endl;
354 // Check needed to survive LyX startup
358 if (lyxerr.debugging(Debug::WORKAREA)) {
359 lyxerr[Debug::WORKAREA] << "BufferView::update" << std::endl;
362 // Update macro store
363 buffer_->buildMacros();
365 // First drawing step
366 updateMetrics(flags & Update::SinglePar);
368 // The second drawing step is done in WorkArea::redraw() if needed.
369 bool const need_second_step =
370 (flags & (Update::Force | Update::FitCursor | Update::MultiParSel))
371 && (fitCursor() || multiParSel());
373 return need_second_step;
377 void BufferView::updateScrollbar()
380 lyxerr[Debug::DEBUG] << BOOST_CURRENT_FUNCTION
381 << " no text in updateScrollbar" << endl;
382 scrollbarParameters_.reset();
386 LyXText & t = buffer_->text();
387 int const parsize = int(t.paragraphs().size() - 1);
388 if (anchor_ref_ > parsize) {
389 anchor_ref_ = parsize;
393 if (lyxerr.debugging(Debug::GUI)) {
395 << BOOST_CURRENT_FUNCTION
396 << " Updating scrollbar: height: " << t.paragraphs().size()
397 << " curr par: " << cursor_.bottom().pit()
398 << " default height " << defaultRowHeight() << endl;
401 // It would be better to fix the scrollbar to understand
402 // values in [0..1] and divide everything by wh
404 // estimated average paragraph height:
407 int h = t.getPar(anchor_ref_).height();
409 // Normalize anchor/offset (MV):
410 while (offset_ref_ > h && anchor_ref_ < parsize) {
413 h = t.getPar(anchor_ref_).height();
415 // Look at paragraph heights on-screen
418 for (pit_type pit = anchor_ref_; pit <= parsize; ++pit) {
421 int const h2 = t.getPar(pit).height();
427 int const hav = sumh / nh;
428 // More realistic average paragraph height
433 scrollbarParameters_.height = (parsize + 1) * wh_;
434 scrollbarParameters_.position = anchor_ref_ * wh_ + int(offset_ref_ * wh_ / float(h));
435 scrollbarParameters_.lineScrollHeight = int(wh_ * defaultRowHeight() / float(h));
439 ScrollbarParameters const & BufferView::scrollbarParameters() const
441 return scrollbarParameters_;
445 void BufferView::scrollDocView(int value)
447 lyxerr[Debug::GUI] << BOOST_CURRENT_FUNCTION
448 << "[ value = " << value << "]" << endl;
453 LyXText & t = buffer_->text();
455 float const bar = value / float(wh_ * t.paragraphs().size());
457 anchor_ref_ = int(bar * t.paragraphs().size());
458 if (anchor_ref_ > int(t.paragraphs().size()) - 1)
459 anchor_ref_ = int(t.paragraphs().size()) - 1;
460 t.redoParagraph(*this, anchor_ref_);
461 int const h = t.getPar(anchor_ref_).height();
462 offset_ref_ = int((bar * t.paragraphs().size() - anchor_ref_) * h);
466 void BufferView::setCursorFromScrollbar()
468 LyXText & t = buffer_->text();
470 int const height = 2 * defaultRowHeight();
471 int const first = height;
472 int const last = height_ - height;
473 LCursor & cur = cursor_;
475 bv_funcs::CurStatus st = bv_funcs::status(this, cur);
478 case bv_funcs::CUR_ABOVE:
479 t.setCursorFromCoordinates(cur, 0, first);
480 cur.clearSelection();
482 case bv_funcs::CUR_BELOW:
483 t.setCursorFromCoordinates(cur, 0, last);
484 cur.clearSelection();
486 case bv_funcs::CUR_INSIDE:
487 int const y = bv_funcs::getPos(*this, cur, cur.boundary()).y_;
488 int const newy = min(last, max(y, first));
490 cur.reset(buffer_->inset());
491 t.setCursorFromCoordinates(cur, 0, newy);
497 Change const BufferView::getCurrentChange() const
499 if (!cursor_.selection())
500 return Change(Change::UNCHANGED);
502 DocIterator dit = cursor_.selectionBegin();
503 return dit.paragraph().lookupChange(dit.pos());
507 void BufferView::saveBookmark(bool persistent)
509 LyX::ref().session().bookmarks().save(
511 cursor_.paragraph().id(),
516 // emit message signal.
517 message(_("Save bookmark"));
521 void BufferView::moveToPosition(int par_id, pos_type par_pos)
523 cursor_.clearSelection();
525 ParIterator par = buffer_->getParFromID(par_id);
526 if (par == buffer_->par_iterator_end())
529 setCursor(makeDocIterator(par, min(par->size(), par_pos)));
533 void BufferView::switchKeyMap()
535 if (!lyxrc.rtl_support)
538 if (getLyXText()->real_current_font.isRightToLeft()) {
539 if (intl_->keymap == Intl::PRIMARY)
542 if (intl_->keymap == Intl::SECONDARY)
548 int BufferView::workWidth() const
554 void BufferView::center()
556 CursorSlice & bot = cursor_.bottom();
557 pit_type const pit = bot.pit();
558 bot.text()->redoParagraph(*this, pit);
559 Paragraph const & par = bot.text()->paragraphs()[pit];
561 offset_ref_ = bv_funcs::coordOffset(*this, cursor_, cursor_.boundary()).y_
562 + par.ascent() - height_ / 2;
566 FuncStatus BufferView::getStatus(FuncRequest const & cmd)
570 switch (cmd.action) {
573 flag.enabled(!buffer_->undostack().empty());
576 flag.enabled(!buffer_->redostack().empty());
578 case LFUN_FILE_INSERT:
579 case LFUN_FILE_INSERT_ASCII_PARA:
580 case LFUN_FILE_INSERT_ASCII:
581 case LFUN_BOOKMARK_SAVE:
582 // FIXME: Actually, these LFUNS should be moved to LyXText
583 flag.enabled(cursor_.inTexted());
585 case LFUN_FONT_STATE:
586 case LFUN_LABEL_INSERT:
587 case LFUN_PARAGRAPH_GOTO:
588 // FIXME handle non-trivially
589 case LFUN_OUTLINE_UP:
590 case LFUN_OUTLINE_DOWN:
591 case LFUN_OUTLINE_IN:
592 case LFUN_OUTLINE_OUT:
594 case LFUN_REFERENCE_NEXT:
596 case LFUN_WORD_REPLACE:
599 case LFUN_MARK_TOGGLE:
600 case LFUN_SCREEN_RECENTER:
601 case LFUN_BIBTEX_DATABASE_ADD:
602 case LFUN_BIBTEX_DATABASE_DEL:
603 case LFUN_WORDS_COUNT:
604 case LFUN_NEXT_INSET_TOGGLE:
608 case LFUN_LABEL_GOTO: {
609 flag.enabled(!cmd.argument().empty()
610 || getInsetByCode<InsetRef>(cursor_, InsetBase::REF_CODE));
614 case LFUN_CHANGES_TRACK:
616 flag.setOnOff(buffer_->params().trackChanges);
619 case LFUN_CHANGES_OUTPUT: {
620 OutputParams runparams;
621 LaTeXFeatures features(*buffer_, buffer_->params(), runparams);
622 flag.enabled(buffer_ && features.isAvailable("dvipost"));
623 flag.setOnOff(buffer_->params().outputChanges);
627 case LFUN_CHANGES_MERGE:
628 case LFUN_CHANGE_NEXT:
629 case LFUN_ALL_CHANGES_ACCEPT:
630 case LFUN_ALL_CHANGES_REJECT:
631 flag.enabled(buffer_); // FIXME: Change tracking (MG)
634 case LFUN_BUFFER_TOGGLE_COMPRESSION: {
635 flag.setOnOff(buffer_->params().compressed);
647 bool BufferView::dispatch(FuncRequest const & cmd)
649 //lyxerr << BOOST_CURRENT_FUNCTION
650 // << [ cmd = " << cmd << "]" << endl;
652 // Make sure that the cached BufferView is correct.
653 lyxerr[Debug::ACTION] << BOOST_CURRENT_FUNCTION
654 << " action[" << cmd.action << ']'
655 << " arg[" << to_utf8(cmd.argument()) << ']'
656 << " x[" << cmd.x << ']'
657 << " y[" << cmd.y << ']'
658 << " button[" << cmd.button() << ']'
661 LCursor & cur = cursor_;
663 switch (cmd.action) {
667 cur.message(_("Undo"));
668 cur.clearSelection();
669 if (!textUndo(*this))
670 cur.message(_("No further undo information"));
678 cur.message(_("Redo"));
679 cur.clearSelection();
680 if (!textRedo(*this))
681 cur.message(_("No further redo information"));
687 case LFUN_FILE_INSERT:
688 // FIXME: We don't know the encoding of filenames
689 menuInsertLyXFile(to_utf8(cmd.argument()));
692 case LFUN_FILE_INSERT_ASCII_PARA:
693 // FIXME: We don't know the encoding of filenames
694 insertAsciiFile(this, to_utf8(cmd.argument()), true);
697 case LFUN_FILE_INSERT_ASCII:
698 // FIXME: We don't know the encoding of filenames
699 insertAsciiFile(this, to_utf8(cmd.argument()), false);
702 case LFUN_FONT_STATE:
703 cur.message(from_utf8(cur.currentState()));
706 case LFUN_BOOKMARK_SAVE:
707 saveBookmark(convert<unsigned int>(to_utf8(cmd.argument())));
710 case LFUN_LABEL_GOTO: {
711 docstring label = cmd.argument();
714 getInsetByCode<InsetRef>(cursor_,
715 InsetBase::REF_CODE);
717 label = inset->getParam("reference");
718 // persistent=false: use temp_bookmark
728 case LFUN_PARAGRAPH_GOTO: {
729 int const id = convert<int>(to_utf8(cmd.argument()));
730 ParIterator par = buffer_->getParFromID(id);
731 if (par == buffer_->par_iterator_end()) {
732 lyxerr[Debug::INFO] << "No matching paragraph found! ["
733 << id << ']' << endl;
736 lyxerr[Debug::INFO] << "Paragraph " << par->id()
737 << " found." << endl;
741 setCursor(makeDocIterator(par, 0));
748 case LFUN_OUTLINE_UP:
749 toc::outline(toc::Up, cursor_);
750 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
751 updateLabels(*buffer_);
753 case LFUN_OUTLINE_DOWN:
754 toc::outline(toc::Down, cursor_);
755 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
756 updateLabels(*buffer_);
758 case LFUN_OUTLINE_IN:
759 toc::outline(toc::In, cursor_);
760 updateLabels(*buffer_);
762 case LFUN_OUTLINE_OUT:
763 toc::outline(toc::Out, cursor_);
764 updateLabels(*buffer_);
768 bv_funcs::gotoInset(this, InsetBase::NOTE_CODE, false);
771 case LFUN_REFERENCE_NEXT: {
772 vector<InsetBase_code> tmp;
773 tmp.push_back(InsetBase::LABEL_CODE);
774 tmp.push_back(InsetBase::REF_CODE);
775 bv_funcs::gotoInset(this, tmp, true);
779 case LFUN_CHANGES_TRACK:
780 buffer_->params().trackChanges = !buffer_->params().trackChanges;
783 case LFUN_CHANGES_OUTPUT: {
784 buffer_->params().outputChanges = !buffer_->params().outputChanges;
788 case LFUN_CHANGE_NEXT:
789 findNextChange(this);
792 case LFUN_CHANGES_MERGE:
793 if (findNextChange(this))
794 showDialog("changes");
797 case LFUN_ALL_CHANGES_ACCEPT: {
798 cursor_.reset(buffer_->inset());
800 #warning FIXME changes
802 while (findNextChange(this))
803 getLyXText()->acceptChange(cursor_);
808 case LFUN_ALL_CHANGES_REJECT: {
809 cursor_.reset(buffer_->inset());
811 #warning FIXME changes
813 while (findNextChange(this))
814 getLyXText()->rejectChange(cursor_);
822 case LFUN_WORD_REPLACE:
827 cur.clearSelection();
829 cur.message(from_utf8(N_("Mark off")));
833 cur.clearSelection();
836 cur.message(from_utf8(N_("Mark on")));
839 case LFUN_MARK_TOGGLE:
840 cur.clearSelection();
843 cur.message(from_utf8(N_("Mark removed")));
846 cur.message(from_utf8(N_("Mark set")));
851 case LFUN_SCREEN_RECENTER:
855 case LFUN_BIBTEX_DATABASE_ADD: {
856 LCursor tmpcur = cursor_;
857 bv_funcs::findInset(tmpcur, InsetBase::BIBTEX_CODE, false);
858 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
859 InsetBase::BIBTEX_CODE);
861 if (inset->addDatabase(to_utf8(cmd.argument())))
862 buffer_->updateBibfilesCache();
867 case LFUN_BIBTEX_DATABASE_DEL: {
868 LCursor tmpcur = cursor_;
869 bv_funcs::findInset(tmpcur, InsetBase::BIBTEX_CODE, false);
870 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
871 InsetBase::BIBTEX_CODE);
873 if (inset->delDatabase(to_utf8(cmd.argument())))
874 buffer_->updateBibfilesCache();
879 case LFUN_WORDS_COUNT: {
880 DocIterator from, to;
881 if (cur.selection()) {
882 from = cur.selectionBegin();
883 to = cur.selectionEnd();
885 from = doc_iterator_begin(buffer_->inset());
886 to = doc_iterator_end(buffer_->inset());
888 int const count = countWords(from, to);
892 message = bformat(_("%1$d words in selection."),
895 message = bformat(_("%1$d words in document."),
900 message = _("One word in selection.");
902 message = _("One word in document.");
905 Alert::information(_("Count words"), message);
909 case LFUN_BUFFER_TOGGLE_COMPRESSION:
910 // turn compression on/off
911 buffer_->params().compressed = !buffer_->params().compressed;
914 case LFUN_NEXT_INSET_TOGGLE: {
915 // this is the real function we want to invoke
916 FuncRequest tmpcmd = FuncRequest(LFUN_INSET_TOGGLE, cmd.origin);
917 // if there is an inset at cursor, see whether it
919 InsetBase * inset = cur.nextInset();
920 if (inset && inset->isActive()) {
921 LCursor tmpcur = cur;
922 tmpcur.pushLeft(*inset);
923 inset->dispatch(tmpcur, tmpcmd);
924 if (tmpcur.result().dispatched()) {
928 // if it did not work, try the underlying inset.
929 if (!cur.result().dispatched())
930 cur.dispatch(tmpcmd);
932 if (cur.result().dispatched())
933 cur.clearSelection();
946 docstring const BufferView::requestSelection()
951 LCursor & cur = cursor_;
953 if (!cur.selection()) {
954 xsel_cache_.set = false;
958 if (!xsel_cache_.set ||
959 cur.top() != xsel_cache_.cursor ||
960 cur.anchor_.top() != xsel_cache_.anchor)
962 xsel_cache_.cursor = cur.top();
963 xsel_cache_.anchor = cur.anchor_.top();
964 xsel_cache_.set = cur.selection();
965 return cur.selectionAsString(false);
971 void BufferView::clearSelection()
974 cursor_.clearSelection();
975 xsel_cache_.set = false;
980 void BufferView::workAreaResize(int width, int height)
982 bool const widthChange = width != width_;
983 bool const heightChange = height != height_;
985 // Update from work area
996 bool BufferView::workAreaDispatch(FuncRequest const & cmd0)
998 //lyxerr << BOOST_CURRENT_FUNCTION << "[ cmd0 " << cmd0 << "]" << endl;
1000 // This is only called for mouse related events including
1001 // LFUN_FILE_OPEN generated by drag-and-drop.
1002 FuncRequest cmd = cmd0;
1008 cur.push(buffer_->inset());
1009 cur.selection() = cursor_.selection();
1011 // Doesn't go through lyxfunc, so we need to update
1012 // the layout choice etc. ourselves
1014 // E.g. Qt mouse press when no buffer
1018 // Either the inset under the cursor or the
1019 // surrounding LyXText will handle this event.
1021 // Build temporary cursor.
1022 cmd.y = min(max(cmd.y, -1), height_);
1023 InsetBase * inset = buffer_->text().editXY(cur, cmd.x, cmd.y);
1024 //lyxerr << BOOST_CURRENT_FUNCTION
1025 // << " * hit inset at tip: " << inset << endl;
1026 //lyxerr << BOOST_CURRENT_FUNCTION
1027 // << " * created temp cursor:" << cur << endl;
1029 // Put anchor at the same position.
1032 // Try to dispatch to an non-editable inset near this position
1033 // via the temp cursor. If the inset wishes to change the real
1034 // cursor it has to do so explicitly by using
1035 // cur.bv().cursor() = cur; (or similar)
1037 inset->dispatch(cur, cmd);
1039 // Now dispatch to the temporary cursor. If the real cursor should
1040 // be modified, the inset's dispatch has to do so explicitly.
1041 if (!cur.result().dispatched())
1044 if (cur.result().dispatched()) {
1045 // Redraw if requested or necessary.
1046 if (cur.result().update())
1047 update(Update::FitCursor | Update::Force);
1049 update(Update::FitCursor | Update::MultiParSel);
1056 void BufferView::scroll(int /*lines*/)
1061 // LyXText const * t = &buffer_->text();
1062 // int const line_height = defaultRowHeight();
1064 // // The new absolute coordinate
1065 // int new_top_y = top_y() + lines * line_height;
1067 // // Restrict to a valid value
1068 // new_top_y = std::min(t->height() - 4 * line_height, new_top_y);
1069 // new_top_y = std::max(0, new_top_y);
1071 // scrollDocView(new_top_y);
1073 // // Update the scrollbar.
1074 // workArea_->setScrollbarParams(t->height(), top_y(), defaultRowHeight());}
1078 void BufferView::setCursorFromRow(int row)
1083 buffer_->texrow().getIdFromRow(row, tmpid, tmppos);
1086 buffer_->text().setCursor(cursor_, 0, 0);
1088 buffer_->text().setCursor(cursor_, buffer_->getParFromID(tmpid).pit(), tmppos);
1092 void BufferView::gotoLabel(docstring const & label)
1094 for (InsetIterator it = inset_iterator_begin(buffer_->inset()); it; ++it) {
1095 vector<docstring> labels;
1096 it->getLabelList(*buffer_, labels);
1097 if (std::find(labels.begin(), labels.end(), label) != labels.end()) {
1106 LyXText * BufferView::getLyXText()
1108 LyXText * text = cursor_.innerText();
1114 LyXText const * BufferView::getLyXText() const
1116 LyXText const * text = cursor_.innerText();
1122 int BufferView::workHeight() const
1128 void BufferView::setCursor(DocIterator const & dit)
1130 size_t const n = dit.depth();
1131 for (size_t i = 0; i < n; ++i)
1132 dit[i].inset().edit(cursor_, true);
1134 cursor_.setCursor(dit);
1135 cursor_.selection() = false;
1139 void BufferView::mouseSetCursor(LCursor & cur)
1141 BOOST_ASSERT(&cur.bv() == this);
1143 // Has the cursor just left the inset?
1144 bool badcursor = false;
1145 if (&cursor_.inset() != &cur.inset())
1146 badcursor = cursor_.inset().notifyCursorLeaves(cursor_);
1148 // do the dEPM magic if needed
1149 // FIXME: move this to InsetText::notifyCursorLeaves?
1150 if (!badcursor && cursor_.inTexted())
1151 cursor_.text()->deleteEmptyParagraphMechanism(cur, cursor_);
1154 cursor_.clearSelection();
1155 cursor_.setTargetX();
1161 void BufferView::putSelectionAt(DocIterator const & cur,
1162 int length, bool backwards)
1164 cursor_.clearSelection();
1170 cursor_.pos() += length;
1171 cursor_.setSelection(cursor_, -length);
1173 cursor_.setSelection(cursor_, length);
1178 LCursor & BufferView::cursor()
1184 LCursor const & BufferView::cursor() const
1190 pit_type BufferView::anchor_ref() const
1196 ViewMetricsInfo const & BufferView::viewMetricsInfo()
1198 return metrics_info_;
1202 void BufferView::updateMetrics(bool singlepar)
1204 // FIXME (Abdel 19/10/2006):
1205 // There's something fishy in tabular. The coord_cache_ is not
1206 // correctly reconstructed when a character is trying to be inserted.
1207 // Not clearing out the coord_cache_ fixes the crash but there is a
1208 // bad side effect: buffer-begin and buffer-end do not update the screen.
1210 // Remove old position cache
1211 coord_cache_.clear();
1213 LyXText & buftext = buffer_->text();
1214 pit_type size = int(buftext.paragraphs().size());
1216 if (anchor_ref_ > int(buftext.paragraphs().size() - 1)) {
1217 anchor_ref_ = int(buftext.paragraphs().size() - 1);
1221 pit_type const pit = anchor_ref_;
1224 size_t const npit = buftext.paragraphs().size();
1226 // Rebreak anchor paragraph. In Single Paragraph mode, rebreak only
1227 // the (main text, not inset!) paragraph containing the cursor.
1228 // (if this paragraph contains insets etc., rebreaking will
1229 // recursively descend)
1230 if (!singlepar || pit == cursor_.bottom().pit())
1231 buftext.redoParagraph(*this, pit);
1232 int y0 = buftext.getPar(pit).ascent() - offset_ref_;
1234 // Redo paragraphs above anchor if necessary; again, in Single Par
1235 // mode, only if we encounter the (main text) one having the cursor.
1237 while (y1 > 0 && pit1 > 0) {
1238 y1 -= buftext.getPar(pit1).ascent();
1240 if (!singlepar || pit1 == cursor_.bottom().pit())
1241 buftext.redoParagraph(*this, pit1);
1242 y1 -= buftext.getPar(pit1).descent();
1246 // Take care of ascent of first line
1247 y1 -= buftext.getPar(pit1).ascent();
1249 // Normalize anchor for next time
1253 // Grey at the beginning is ugly
1254 if (pit1 == 0 && y1 > 0) {
1260 // Redo paragraphs below the anchor if necessary. Single par mode:
1261 // only the one containing the cursor if encountered.
1263 while (y2 < height_ && pit2 < int(npit) - 1) {
1264 y2 += buftext.getPar(pit2).descent();
1266 if (!singlepar || pit2 == cursor_.bottom().pit())
1267 buftext.redoParagraph(*this, pit2);
1268 y2 += buftext.getPar(pit2).ascent();
1271 // Take care of descent of last line
1272 y2 += buftext.getPar(pit2).descent();
1274 // The coordinates of all these paragraphs are correct, cache them
1276 CoordCache::InnerParPosCache & parPos = coord_cache_.parPos()[&buftext];
1277 for (pit_type pit = pit1; pit <= pit2; ++pit) {
1278 Paragraph const & par = buftext.getPar(pit);
1280 parPos[pit] = Point(0, y);
1281 if (singlepar && pit == cursor_.bottom().pit()) {
1282 // In Single Paragraph mode, collect here the
1283 // y1 and y2 of the (one) paragraph the cursor is in
1284 y1 = y - par.ascent();
1285 y2 = y + par.descent();
1291 // collect cursor paragraph iter bounds
1292 pit1 = cursor_.bottom().pit();
1293 pit2 = cursor_.bottom().pit();
1296 lyxerr[Debug::DEBUG]
1297 << BOOST_CURRENT_FUNCTION
1300 << " pit1: " << pit1
1301 << " pit2: " << pit2
1302 << " npit: " << npit
1303 << " singlepar: " << singlepar
1307 metrics_info_ = ViewMetricsInfo(pit1, pit2, y1, y2, singlepar, size);
1309 if (lyxerr.debugging(Debug::WORKAREA)) {
1310 lyxerr[Debug::WORKAREA] << "BufferView::updateMetrics" << endl;
1311 coord_cache_.dump();
1316 void BufferView::menuInsertLyXFile(string const & filenm)
1318 BOOST_ASSERT(cursor_.inTexted());
1319 string filename = filenm;
1321 if (filename.empty()) {
1322 // Launch a file browser
1324 string initpath = lyxrc.document_path;
1327 string const trypath = buffer_->filePath();
1328 // If directory is writeable, use this as default.
1329 if (isDirWriteable(trypath))
1334 FileDialog fileDlg(_("Select LyX document to insert"),
1336 make_pair(_("Documents|#o#O"), from_utf8(lyxrc.document_path)),
1337 make_pair(_("Examples|#E#e"), from_utf8(addPath(package().system_support(), "examples"))));
1339 FileDialog::Result result =
1340 fileDlg.open(from_utf8(initpath),
1341 FileFilterList(_("LyX Documents (*.lyx)")),
1344 if (result.first == FileDialog::Later)
1348 filename = to_utf8(result.second);
1350 // check selected filename
1351 if (filename.empty()) {
1352 // emit message signal.
1353 message(_("Canceled."));
1358 // Get absolute path of file and add ".lyx"
1359 // to the filename if necessary
1360 filename = fileSearch(string(), filename, "lyx");
1362 docstring const disp_fn = makeDisplayPath(filename);
1363 // emit message signal.
1364 message(bformat(_("Inserting document %1$s..."), disp_fn));
1367 Buffer buf("", false);
1368 if (lyx::loadLyXFile(&buf, makeAbsPath(filename))) {
1369 ErrorList & el = buffer_->errorList("Parse");
1370 // Copy the inserted document error list into the current buffer one.
1371 el = buf.errorList("Parse");
1372 cap::pasteParagraphList(cursor_, buf.paragraphs(),
1373 buf.params().textclass, el);
1374 res = _("Document %1$s inserted.");
1376 res = _("Could not insert document %1$s");
1378 // emit message signal.
1379 message(bformat(res, disp_fn));
1380 buffer_->errors("Parse");