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();
201 updateMetrics(false);
203 if (buffer_ && graphics::Previews::status() != LyXRC::PREVIEW_OFF)
204 graphics::Previews::get().generateBufferPreviews(*buffer_);
208 bool BufferView::loadLyXFile(string const & filename, bool tolastfiles)
210 // Get absolute path of file and add ".lyx"
211 // to the filename if necessary
212 string s = fileSearch(string(), filename, "lyx");
214 bool const found = !s.empty();
219 // File already open?
220 if (theBufferList().exists(s)) {
221 docstring const file = makeDisplayPath(s, 20);
222 docstring text = bformat(_("The document %1$s is already "
223 "loaded.\n\nDo you want to revert "
224 "to the saved version?"), file);
225 int const ret = Alert::prompt(_("Revert to saved document?"),
226 text, 0, 1, _("&Revert"), _("&Switch to document"));
229 setBuffer(theBufferList().getBuffer(s));
232 // FIXME: should be LFUN_REVERT
233 if (!theBufferList().close(theBufferList().getBuffer(s), false))
235 // Fall through to new load. (Asger)
242 b = theBufferList().newBuffer(s);
243 if (!lyx::loadLyXFile(b, s)) {
244 theBufferList().release(b);
248 docstring text = bformat(_("The document %1$s does not yet "
249 "exist.\n\nDo you want to create "
250 "a new document?"), from_utf8(s));
251 int const ret = Alert::prompt(_("Create new document?"),
252 text, 0, 1, _("&Create"), _("Cancel"));
255 b = newFile(s, string(), true);
263 // Send the "errors" signal in case of parsing errors
266 // scroll to the position when the file was last closed
267 if (lyxrc.use_lastfilepos) {
270 boost::tie(pit, pos) = LyX::ref().session().lastFilePos().load(s);
271 // I am not sure how to separate the following part to a function
272 // so I will leave this to Lars.
274 // check pit since the document may be externally changed.
275 if ( static_cast<size_t>(pit) < b->paragraphs().size() ) {
276 ParIterator it = b->par_iterator_begin();
277 ParIterator const end = b->par_iterator_end();
278 for (; it != end; ++it)
279 if (it.pit() == pit) {
280 // restored pos may be bigger than it->size
281 setCursor(makeDocIterator(it, min(pos, it->size())));
282 // No need to update the metrics if fitCursor returns false.
284 updateMetrics(false);
291 LyX::ref().session().lastFiles().add(b->fileName());
297 void BufferView::reload()
299 string const fn = buffer_->fileName();
300 if (theBufferList().close(buffer_, false))
305 void BufferView::resize()
310 lyxerr[Debug::DEBUG] << BOOST_CURRENT_FUNCTION << endl;
312 buffer_->text().init(this);
318 bool BufferView::fitCursor()
320 if (bv_funcs::status(this, cursor_) == bv_funcs::CUR_INSIDE) {
321 frontend::FontMetrics const & fm =
322 theFontMetrics(cursor_.getFont());
323 int const asc = fm.maxAscent();
324 int const des = fm.maxDescent();
325 Point const p = bv_funcs::getPos(*this, cursor_, cursor_.boundary());
326 if (p.y_ - asc >= 0 && p.y_ + des < height_)
334 bool BufferView::multiParSel()
336 if (!cursor_.selection())
338 bool ret = multiparsel_cache_;
339 multiparsel_cache_ = cursor_.selBegin().pit() != cursor_.selEnd().pit();
340 // Either this, or previous selection spans paragraphs
341 return ret || multiparsel_cache_;
345 std::pair<bool, bool> BufferView::update(Update::flags flags)
347 // This is close to a hot-path.
348 if (lyxerr.debugging(Debug::DEBUG)) {
350 << BOOST_CURRENT_FUNCTION
351 << "[fitcursor = " << (flags & Update::FitCursor)
352 << ", forceupdate = " << (flags & Update::Force)
353 << ", singlepar = " << (flags & Update::SinglePar)
354 << "] buffer: " << buffer_ << endl;
357 // Check needed to survive LyX startup
359 return make_pair(false, false);
361 if (lyxerr.debugging(Debug::WORKAREA)) {
362 lyxerr[Debug::WORKAREA] << "BufferView::update" << std::endl;
365 // Update macro store
366 buffer_->buildMacros();
368 // Now do the first drawing step if needed. This consists on updating
369 // the CoordCache in updateMetrics().
370 // The second drawing step is done in WorkArea::redraw() if needed.
372 // Case when no explicit update is requested.
374 // no need to do anything.
375 return make_pair(false, false);
378 bool full_metrics = flags & Update::Force;
379 if (flags & Update::MultiParSel)
380 full_metrics |= multiParSel();
382 bool const single_par = !full_metrics;
383 updateMetrics(single_par);
385 if (flags & Update::FitCursor && fitCursor())
386 updateMetrics(false);
388 // tell the frontend to update the screen.
389 return make_pair(true, single_par);
393 void BufferView::updateScrollbar()
396 lyxerr[Debug::DEBUG] << BOOST_CURRENT_FUNCTION
397 << " no text in updateScrollbar" << endl;
398 scrollbarParameters_.reset();
402 LyXText & t = buffer_->text();
403 int const parsize = int(t.paragraphs().size() - 1);
404 if (anchor_ref_ > parsize) {
405 anchor_ref_ = parsize;
409 if (lyxerr.debugging(Debug::GUI)) {
411 << BOOST_CURRENT_FUNCTION
412 << " Updating scrollbar: height: " << t.paragraphs().size()
413 << " curr par: " << cursor_.bottom().pit()
414 << " default height " << defaultRowHeight() << endl;
417 // It would be better to fix the scrollbar to understand
418 // values in [0..1] and divide everything by wh
420 // estimated average paragraph height:
423 int h = t.getPar(anchor_ref_).height();
425 // Normalize anchor/offset (MV):
426 while (offset_ref_ > h && anchor_ref_ < parsize) {
429 h = t.getPar(anchor_ref_).height();
431 // Look at paragraph heights on-screen
434 for (pit_type pit = anchor_ref_; pit <= parsize; ++pit) {
437 int const h2 = t.getPar(pit).height();
443 int const hav = sumh / nh;
444 // More realistic average paragraph height
449 scrollbarParameters_.height = (parsize + 1) * wh_;
450 scrollbarParameters_.position = anchor_ref_ * wh_ + int(offset_ref_ * wh_ / float(h));
451 scrollbarParameters_.lineScrollHeight = int(wh_ * defaultRowHeight() / float(h));
455 ScrollbarParameters const & BufferView::scrollbarParameters() const
457 return scrollbarParameters_;
461 void BufferView::scrollDocView(int value)
463 lyxerr[Debug::GUI] << BOOST_CURRENT_FUNCTION
464 << "[ value = " << value << "]" << endl;
469 LyXText & t = buffer_->text();
471 float const bar = value / float(wh_ * t.paragraphs().size());
473 anchor_ref_ = int(bar * t.paragraphs().size());
474 if (anchor_ref_ > int(t.paragraphs().size()) - 1)
475 anchor_ref_ = int(t.paragraphs().size()) - 1;
476 t.redoParagraph(*this, anchor_ref_);
477 int const h = t.getPar(anchor_ref_).height();
478 offset_ref_ = int((bar * t.paragraphs().size() - anchor_ref_) * h);
479 updateMetrics(false);
483 void BufferView::setCursorFromScrollbar()
485 LyXText & t = buffer_->text();
487 int const height = 2 * defaultRowHeight();
488 int const first = height;
489 int const last = height_ - height;
490 LCursor & cur = cursor_;
492 bv_funcs::CurStatus st = bv_funcs::status(this, cur);
495 case bv_funcs::CUR_ABOVE:
496 t.setCursorFromCoordinates(cur, 0, first);
497 cur.clearSelection();
499 case bv_funcs::CUR_BELOW:
500 t.setCursorFromCoordinates(cur, 0, last);
501 cur.clearSelection();
503 case bv_funcs::CUR_INSIDE:
504 int const y = bv_funcs::getPos(*this, cur, cur.boundary()).y_;
505 int const newy = min(last, max(y, first));
507 cur.reset(buffer_->inset());
508 t.setCursorFromCoordinates(cur, 0, newy);
514 Change const BufferView::getCurrentChange() const
516 if (!cursor_.selection())
517 return Change(Change::UNCHANGED);
519 DocIterator dit = cursor_.selectionBegin();
520 return dit.paragraph().lookupChange(dit.pos());
524 void BufferView::saveBookmark(bool persistent)
526 LyX::ref().session().bookmarks().save(
528 cursor_.paragraph().id(),
533 // emit message signal.
534 message(_("Save bookmark"));
538 void BufferView::moveToPosition(int par_id, pos_type par_pos)
540 cursor_.clearSelection();
542 ParIterator par = buffer_->getParFromID(par_id);
543 if (par == buffer_->par_iterator_end())
546 setCursor(makeDocIterator(par, min(par->size(), par_pos)));
550 void BufferView::switchKeyMap()
552 if (!lyxrc.rtl_support)
555 if (getLyXText()->real_current_font.isRightToLeft()) {
556 if (intl_->keymap == Intl::PRIMARY)
559 if (intl_->keymap == Intl::SECONDARY)
565 int BufferView::workWidth() const
571 void BufferView::center()
573 CursorSlice & bot = cursor_.bottom();
574 pit_type const pit = bot.pit();
575 bot.text()->redoParagraph(*this, pit);
576 Paragraph const & par = bot.text()->paragraphs()[pit];
578 offset_ref_ = bv_funcs::coordOffset(*this, cursor_, cursor_.boundary()).y_
579 + par.ascent() - height_ / 2;
583 FuncStatus BufferView::getStatus(FuncRequest const & cmd)
587 switch (cmd.action) {
590 flag.enabled(!buffer_->undostack().empty());
593 flag.enabled(!buffer_->redostack().empty());
595 case LFUN_FILE_INSERT:
596 case LFUN_FILE_INSERT_ASCII_PARA:
597 case LFUN_FILE_INSERT_ASCII:
598 case LFUN_BOOKMARK_SAVE:
599 // FIXME: Actually, these LFUNS should be moved to LyXText
600 flag.enabled(cursor_.inTexted());
602 case LFUN_FONT_STATE:
603 case LFUN_LABEL_INSERT:
604 case LFUN_PARAGRAPH_GOTO:
605 // FIXME handle non-trivially
606 case LFUN_OUTLINE_UP:
607 case LFUN_OUTLINE_DOWN:
608 case LFUN_OUTLINE_IN:
609 case LFUN_OUTLINE_OUT:
611 case LFUN_REFERENCE_NEXT:
613 case LFUN_WORD_REPLACE:
616 case LFUN_MARK_TOGGLE:
617 case LFUN_SCREEN_RECENTER:
618 case LFUN_BIBTEX_DATABASE_ADD:
619 case LFUN_BIBTEX_DATABASE_DEL:
620 case LFUN_WORDS_COUNT:
621 case LFUN_NEXT_INSET_TOGGLE:
625 case LFUN_LABEL_GOTO: {
626 flag.enabled(!cmd.argument().empty()
627 || getInsetByCode<InsetRef>(cursor_, InsetBase::REF_CODE));
631 case LFUN_CHANGES_TRACK:
633 flag.setOnOff(buffer_->params().trackChanges);
636 case LFUN_CHANGES_OUTPUT: {
637 OutputParams runparams;
638 LaTeXFeatures features(*buffer_, buffer_->params(), runparams);
639 flag.enabled(buffer_ && features.isAvailable("dvipost"));
640 flag.setOnOff(buffer_->params().outputChanges);
644 case LFUN_CHANGES_MERGE:
645 case LFUN_CHANGE_NEXT:
646 case LFUN_ALL_CHANGES_ACCEPT:
647 case LFUN_ALL_CHANGES_REJECT:
648 flag.enabled(buffer_); // FIXME: Change tracking (MG)
651 case LFUN_BUFFER_TOGGLE_COMPRESSION: {
652 flag.setOnOff(buffer_->params().compressed);
664 bool BufferView::dispatch(FuncRequest const & cmd)
666 //lyxerr << BOOST_CURRENT_FUNCTION
667 // << [ cmd = " << cmd << "]" << endl;
669 // Make sure that the cached BufferView is correct.
670 lyxerr[Debug::ACTION] << BOOST_CURRENT_FUNCTION
671 << " action[" << cmd.action << ']'
672 << " arg[" << to_utf8(cmd.argument()) << ']'
673 << " x[" << cmd.x << ']'
674 << " y[" << cmd.y << ']'
675 << " button[" << cmd.button() << ']'
678 LCursor & cur = cursor_;
680 switch (cmd.action) {
684 cur.message(_("Undo"));
685 cur.clearSelection();
686 if (!textUndo(*this))
687 cur.message(_("No further undo information"));
695 cur.message(_("Redo"));
696 cur.clearSelection();
697 if (!textRedo(*this))
698 cur.message(_("No further redo information"));
704 case LFUN_FILE_INSERT:
705 // FIXME: We don't know the encoding of filenames
706 menuInsertLyXFile(to_utf8(cmd.argument()));
709 case LFUN_FILE_INSERT_ASCII_PARA:
710 // FIXME: We don't know the encoding of filenames
711 insertAsciiFile(this, to_utf8(cmd.argument()), true);
714 case LFUN_FILE_INSERT_ASCII:
715 // FIXME: We don't know the encoding of filenames
716 insertAsciiFile(this, to_utf8(cmd.argument()), false);
719 case LFUN_FONT_STATE:
720 cur.message(from_utf8(cur.currentState()));
723 case LFUN_BOOKMARK_SAVE:
724 saveBookmark(convert<unsigned int>(to_utf8(cmd.argument())));
727 case LFUN_LABEL_GOTO: {
728 docstring label = cmd.argument();
731 getInsetByCode<InsetRef>(cursor_,
732 InsetBase::REF_CODE);
734 label = inset->getParam("reference");
735 // persistent=false: use temp_bookmark
745 case LFUN_PARAGRAPH_GOTO: {
746 int const id = convert<int>(to_utf8(cmd.argument()));
748 for (Buffer * b = buffer_; i == 0 || b != buffer_; b = theBufferList().next(b)) {
749 ParIterator par = b->getParFromID(id);
750 if (par == b->par_iterator_end()) {
752 << "No matching paragraph found! ["
753 << id << "]." << endl;
756 << "Paragraph " << par->id()
757 << " found in buffer `"
758 << b->fileName() << "'." << endl;
762 setCursor(makeDocIterator(par, 0));
766 // Switch to other buffer view and resend cmd
767 theLyXFunc().dispatch(FuncRequest(
768 LFUN_BUFFER_SWITCH, b->fileName()));
769 theLyXFunc().dispatch(cmd);
778 case LFUN_OUTLINE_UP:
779 toc::outline(toc::Up, cursor_);
780 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
781 updateLabels(*buffer_);
783 case LFUN_OUTLINE_DOWN:
784 toc::outline(toc::Down, cursor_);
785 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
786 updateLabels(*buffer_);
788 case LFUN_OUTLINE_IN:
789 toc::outline(toc::In, cursor_);
790 updateLabels(*buffer_);
792 case LFUN_OUTLINE_OUT:
793 toc::outline(toc::Out, cursor_);
794 updateLabels(*buffer_);
798 bv_funcs::gotoInset(this, InsetBase::NOTE_CODE, false);
801 case LFUN_REFERENCE_NEXT: {
802 vector<InsetBase_code> tmp;
803 tmp.push_back(InsetBase::LABEL_CODE);
804 tmp.push_back(InsetBase::REF_CODE);
805 bv_funcs::gotoInset(this, tmp, true);
809 case LFUN_CHANGES_TRACK:
810 buffer_->params().trackChanges = !buffer_->params().trackChanges;
813 case LFUN_CHANGES_OUTPUT: {
814 buffer_->params().outputChanges = !buffer_->params().outputChanges;
818 case LFUN_CHANGE_NEXT:
819 findNextChange(this);
822 case LFUN_CHANGES_MERGE:
823 if (findNextChange(this))
824 showDialog("changes");
827 case LFUN_ALL_CHANGES_ACCEPT: {
828 cursor_.reset(buffer_->inset());
830 #warning FIXME changes
832 while (findNextChange(this))
833 getLyXText()->acceptChange(cursor_);
838 case LFUN_ALL_CHANGES_REJECT: {
839 cursor_.reset(buffer_->inset());
841 #warning FIXME changes
843 while (findNextChange(this))
844 getLyXText()->rejectChange(cursor_);
852 case LFUN_WORD_REPLACE:
857 cur.clearSelection();
859 cur.message(from_utf8(N_("Mark off")));
863 cur.clearSelection();
866 cur.message(from_utf8(N_("Mark on")));
869 case LFUN_MARK_TOGGLE:
870 cur.clearSelection();
873 cur.message(from_utf8(N_("Mark removed")));
876 cur.message(from_utf8(N_("Mark set")));
881 case LFUN_SCREEN_RECENTER:
885 case LFUN_BIBTEX_DATABASE_ADD: {
886 LCursor tmpcur = cursor_;
887 bv_funcs::findInset(tmpcur, InsetBase::BIBTEX_CODE, false);
888 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
889 InsetBase::BIBTEX_CODE);
891 if (inset->addDatabase(to_utf8(cmd.argument())))
892 buffer_->updateBibfilesCache();
897 case LFUN_BIBTEX_DATABASE_DEL: {
898 LCursor tmpcur = cursor_;
899 bv_funcs::findInset(tmpcur, InsetBase::BIBTEX_CODE, false);
900 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
901 InsetBase::BIBTEX_CODE);
903 if (inset->delDatabase(to_utf8(cmd.argument())))
904 buffer_->updateBibfilesCache();
909 case LFUN_WORDS_COUNT: {
910 DocIterator from, to;
911 if (cur.selection()) {
912 from = cur.selectionBegin();
913 to = cur.selectionEnd();
915 from = doc_iterator_begin(buffer_->inset());
916 to = doc_iterator_end(buffer_->inset());
918 int const count = countWords(from, to);
922 message = bformat(_("%1$d words in selection."),
925 message = bformat(_("%1$d words in document."),
930 message = _("One word in selection.");
932 message = _("One word in document.");
935 Alert::information(_("Count words"), message);
939 case LFUN_BUFFER_TOGGLE_COMPRESSION:
940 // turn compression on/off
941 buffer_->params().compressed = !buffer_->params().compressed;
944 case LFUN_NEXT_INSET_TOGGLE: {
945 // this is the real function we want to invoke
946 FuncRequest tmpcmd = FuncRequest(LFUN_INSET_TOGGLE, cmd.origin);
947 // if there is an inset at cursor, see whether it
949 InsetBase * inset = cur.nextInset();
950 if (inset && inset->isActive()) {
951 LCursor tmpcur = cur;
952 tmpcur.pushLeft(*inset);
953 inset->dispatch(tmpcur, tmpcmd);
954 if (tmpcur.result().dispatched()) {
958 // if it did not work, try the underlying inset.
959 if (!cur.result().dispatched())
960 cur.dispatch(tmpcmd);
962 if (cur.result().dispatched())
963 cur.clearSelection();
976 docstring const BufferView::requestSelection()
981 LCursor & cur = cursor_;
983 if (!cur.selection()) {
984 xsel_cache_.set = false;
988 if (!xsel_cache_.set ||
989 cur.top() != xsel_cache_.cursor ||
990 cur.anchor_.top() != xsel_cache_.anchor)
992 xsel_cache_.cursor = cur.top();
993 xsel_cache_.anchor = cur.anchor_.top();
994 xsel_cache_.set = cur.selection();
995 return cur.selectionAsString(false);
1001 void BufferView::clearSelection()
1004 cursor_.clearSelection();
1005 xsel_cache_.set = false;
1010 void BufferView::workAreaResize(int width, int height)
1012 bool const widthChange = width != width_;
1013 bool const heightChange = height != height_;
1015 // Update from work area
1026 std::pair<bool, bool> BufferView::workAreaDispatch(FuncRequest const & cmd0)
1028 //lyxerr << BOOST_CURRENT_FUNCTION << "[ cmd0 " << cmd0 << "]" << endl;
1030 // This is only called for mouse related events including
1031 // LFUN_FILE_OPEN generated by drag-and-drop.
1032 FuncRequest cmd = cmd0;
1034 // E.g. Qt mouse press when no buffer
1036 return make_pair(false, false);
1039 cur.push(buffer_->inset());
1040 cur.selection() = cursor_.selection();
1042 // Either the inset under the cursor or the
1043 // surrounding LyXText will handle this event.
1045 // Build temporary cursor.
1046 cmd.y = min(max(cmd.y, -1), height_);
1047 InsetBase * inset = buffer_->text().editXY(cur, cmd.x, cmd.y);
1049 //lyxerr << BOOST_CURRENT_FUNCTION
1050 // << " * hit inset at tip: " << inset << endl;
1051 //lyxerr << BOOST_CURRENT_FUNCTION
1052 // << " * created temp cursor:" << cur << endl;
1054 // Put anchor at the same position.
1057 // Try to dispatch to an non-editable inset near this position
1058 // via the temp cursor. If the inset wishes to change the real
1059 // cursor it has to do so explicitly by using
1060 // cur.bv().cursor() = cur; (or similar)
1062 inset->dispatch(cur, cmd);
1065 // Now dispatch to the temporary cursor. If the real cursor should
1066 // be modified, the inset's dispatch has to do so explicitly.
1067 if (!cur.result().dispatched())
1070 // Redraw if requested and necessary.
1071 if (cur.result().dispatched() && cur.result().update())
1072 return update(cur.result().update());
1074 // When the above and the inner function are fixed, we can do this:
1075 return make_pair(false, false);
1079 void BufferView::scroll(int /*lines*/)
1084 // LyXText const * t = &buffer_->text();
1085 // int const line_height = defaultRowHeight();
1087 // // The new absolute coordinate
1088 // int new_top_y = top_y() + lines * line_height;
1090 // // Restrict to a valid value
1091 // new_top_y = std::min(t->height() - 4 * line_height, new_top_y);
1092 // new_top_y = std::max(0, new_top_y);
1094 // scrollDocView(new_top_y);
1096 // // Update the scrollbar.
1097 // workArea_->setScrollbarParams(t->height(), top_y(), defaultRowHeight());}
1101 void BufferView::setCursorFromRow(int row)
1106 buffer_->texrow().getIdFromRow(row, tmpid, tmppos);
1109 buffer_->text().setCursor(cursor_, 0, 0);
1111 buffer_->text().setCursor(cursor_, buffer_->getParFromID(tmpid).pit(), tmppos);
1115 void BufferView::gotoLabel(docstring const & label)
1117 for (InsetIterator it = inset_iterator_begin(buffer_->inset()); it; ++it) {
1118 vector<docstring> labels;
1119 it->getLabelList(*buffer_, labels);
1120 if (std::find(labels.begin(), labels.end(), label) != labels.end()) {
1129 LyXText * BufferView::getLyXText()
1131 LyXText * text = cursor_.innerText();
1137 LyXText const * BufferView::getLyXText() const
1139 LyXText const * text = cursor_.innerText();
1145 int BufferView::workHeight() const
1151 void BufferView::setCursor(DocIterator const & dit)
1153 size_t const n = dit.depth();
1154 for (size_t i = 0; i < n; ++i)
1155 dit[i].inset().edit(cursor_, true);
1157 cursor_.setCursor(dit);
1158 cursor_.selection() = false;
1162 void BufferView::mouseSetCursor(LCursor & cur)
1164 BOOST_ASSERT(&cur.bv() == this);
1166 // Has the cursor just left the inset?
1167 bool badcursor = false;
1168 if (&cursor_.inset() != &cur.inset())
1169 badcursor = cursor_.inset().notifyCursorLeaves(cursor_);
1171 // do the dEPM magic if needed
1172 // FIXME: move this to InsetText::notifyCursorLeaves?
1173 if (!badcursor && cursor_.inTexted())
1174 cursor_.text()->deleteEmptyParagraphMechanism(cur, cursor_);
1177 cursor_.clearSelection();
1178 cursor_.setTargetX();
1184 void BufferView::putSelectionAt(DocIterator const & cur,
1185 int length, bool backwards)
1187 cursor_.clearSelection();
1193 cursor_.pos() += length;
1194 cursor_.setSelection(cursor_, -length);
1196 cursor_.setSelection(cursor_, length);
1201 LCursor & BufferView::cursor()
1207 LCursor const & BufferView::cursor() const
1213 pit_type BufferView::anchor_ref() const
1219 ViewMetricsInfo const & BufferView::viewMetricsInfo()
1221 return metrics_info_;
1225 void BufferView::updateMetrics(bool singlepar)
1227 // Clear out the position cache in case of full screen redraw.
1229 coord_cache_.clear();
1231 LyXText & buftext = buffer_->text();
1232 pit_type size = int(buftext.paragraphs().size());
1234 if (anchor_ref_ > int(buftext.paragraphs().size() - 1)) {
1235 anchor_ref_ = int(buftext.paragraphs().size() - 1);
1239 pit_type const pit = anchor_ref_;
1242 size_t const npit = buftext.paragraphs().size();
1244 // Rebreak anchor paragraph. In Single Paragraph mode, rebreak only
1245 // the (main text, not inset!) paragraph containing the cursor.
1246 // (if this paragraph contains insets etc., rebreaking will
1247 // recursively descend)
1248 if (!singlepar || pit == cursor_.bottom().pit())
1249 buftext.redoParagraph(*this, pit);
1250 int y0 = buftext.getPar(pit).ascent() - offset_ref_;
1252 // Redo paragraphs above anchor if necessary; again, in Single Par
1253 // mode, only if we encounter the (main text) one having the cursor.
1255 while (y1 > 0 && pit1 > 0) {
1256 y1 -= buftext.getPar(pit1).ascent();
1258 if (!singlepar || pit1 == cursor_.bottom().pit())
1259 buftext.redoParagraph(*this, pit1);
1260 y1 -= buftext.getPar(pit1).descent();
1264 // Take care of ascent of first line
1265 y1 -= buftext.getPar(pit1).ascent();
1267 // Normalize anchor for next time
1271 // Grey at the beginning is ugly
1272 if (pit1 == 0 && y1 > 0) {
1278 // Redo paragraphs below the anchor if necessary. Single par mode:
1279 // only the one containing the cursor if encountered.
1281 while (y2 < height_ && pit2 < int(npit) - 1) {
1282 y2 += buftext.getPar(pit2).descent();
1284 if (!singlepar || pit2 == cursor_.bottom().pit())
1285 buftext.redoParagraph(*this, pit2);
1286 y2 += buftext.getPar(pit2).ascent();
1289 // Take care of descent of last line
1290 y2 += buftext.getPar(pit2).descent();
1292 // The coordinates of all these paragraphs are correct, cache them
1294 CoordCache::InnerParPosCache & parPos = coord_cache_.parPos()[&buftext];
1295 for (pit_type pit = pit1; pit <= pit2; ++pit) {
1296 Paragraph const & par = buftext.getPar(pit);
1298 parPos[pit] = Point(0, y);
1299 if (singlepar && pit == cursor_.bottom().pit()) {
1300 // In Single Paragraph mode, collect here the
1301 // y1 and y2 of the (one) paragraph the cursor is in
1302 y1 = y - par.ascent();
1303 y2 = y + par.descent();
1309 // collect cursor paragraph iter bounds
1310 pit1 = cursor_.bottom().pit();
1311 pit2 = cursor_.bottom().pit();
1314 lyxerr[Debug::DEBUG]
1315 << BOOST_CURRENT_FUNCTION
1318 << " pit1: " << pit1
1319 << " pit2: " << pit2
1320 << " npit: " << npit
1321 << " singlepar: " << singlepar
1325 metrics_info_ = ViewMetricsInfo(pit1, pit2, y1, y2, singlepar, size);
1327 if (lyxerr.debugging(Debug::WORKAREA)) {
1328 lyxerr[Debug::WORKAREA] << "BufferView::updateMetrics" << endl;
1329 coord_cache_.dump();
1334 void BufferView::menuInsertLyXFile(string const & filenm)
1336 BOOST_ASSERT(cursor_.inTexted());
1337 string filename = filenm;
1339 if (filename.empty()) {
1340 // Launch a file browser
1342 string initpath = lyxrc.document_path;
1345 string const trypath = buffer_->filePath();
1346 // If directory is writeable, use this as default.
1347 if (isDirWriteable(trypath))
1352 FileDialog fileDlg(_("Select LyX document to insert"),
1354 make_pair(_("Documents|#o#O"), from_utf8(lyxrc.document_path)),
1355 make_pair(_("Examples|#E#e"), from_utf8(addPath(package().system_support(), "examples"))));
1357 FileDialog::Result result =
1358 fileDlg.open(from_utf8(initpath),
1359 FileFilterList(_("LyX Documents (*.lyx)")),
1362 if (result.first == FileDialog::Later)
1366 filename = to_utf8(result.second);
1368 // check selected filename
1369 if (filename.empty()) {
1370 // emit message signal.
1371 message(_("Canceled."));
1376 // Get absolute path of file and add ".lyx"
1377 // to the filename if necessary
1378 filename = fileSearch(string(), filename, "lyx");
1380 docstring const disp_fn = makeDisplayPath(filename);
1381 // emit message signal.
1382 message(bformat(_("Inserting document %1$s..."), disp_fn));
1385 Buffer buf("", false);
1386 if (lyx::loadLyXFile(&buf, makeAbsPath(filename))) {
1387 ErrorList & el = buffer_->errorList("Parse");
1388 // Copy the inserted document error list into the current buffer one.
1389 el = buf.errorList("Parse");
1390 recordUndo(cursor_);
1391 cap::pasteParagraphList(cursor_, buf.paragraphs(),
1392 buf.params().textclass, el);
1393 res = _("Document %1$s inserted.");
1395 res = _("Could not insert document %1$s");
1397 // emit message signal.
1398 message(bformat(res, disp_fn));
1399 buffer_->errors("Parse");