2 * \file buffer_funcs.cpp
3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Lars Gullik Bjønnes
7 * \author Alfredo Braunstein
9 * Full author contact details are available in file CREDITS.
15 #include "buffer_funcs.h"
17 #include "BufferList.h"
18 #include "BufferParams.h"
20 #include "DocIterator.h"
22 #include "ErrorList.h"
24 #include "FloatList.h"
26 #include "InsetList.h"
27 #include "InsetIterator.h"
32 #include "lyxlayout_ptr_fwd.h"
33 #include "TextClass.h"
34 #include "TextClassList.h"
35 #include "Paragraph.h"
36 #include "paragraph_funcs.h"
37 #include "ParagraphList.h"
38 #include "ParagraphParameters.h"
39 #include "ParIterator.h"
43 #include "TocBackend.h"
44 #include "VCBackend.h"
46 #include "frontends/alert.h"
48 #include "insets/InsetBibitem.h"
49 #include "insets/InsetInclude.h"
51 #include "support/filetools.h"
52 #include "support/fs_extras.h"
53 #include "support/lyxlib.h"
55 #include <boost/bind.hpp>
65 using support::bformat;
66 using support::FileName;
67 using support::libFileSearch;
68 using support::makeAbsPath;
69 using support::makeDisplayPath;
70 using support::onlyFilename;
71 using support::onlyPath;
72 using support::unlink;
74 namespace Alert = frontend::Alert;
78 bool readFile(Buffer * const b, FileName const & s)
82 // File information about normal file
84 docstring const file = makeDisplayPath(s.absFilename(), 50);
85 docstring text = bformat(_("The specified document\n%1$s"
86 "\ncould not be read."), file);
87 Alert::error(_("Could not read document"), text);
91 // Check if emergency save file exists and is newer.
92 FileName const e(s.absFilename() + ".emergency");
94 if (e.exists() && s.exists() && e.lastModified() > s.lastModified()) {
95 docstring const file = makeDisplayPath(s.absFilename(), 20);
96 docstring const text =
97 bformat(_("An emergency save of the document "
99 "Recover emergency save?"), file);
100 switch (Alert::prompt(_("Load emergency save?"), text, 0, 2,
101 _("&Recover"), _("&Load Original"),
105 // the file is not saved if we load the emergency file.
107 return b->readFile(e);
115 // Now check if autosave file is newer.
116 FileName const a(onlyPath(s.absFilename()) + '#' + onlyFilename(s.absFilename()) + '#');
118 if (a.exists() && s.exists() && a.lastModified() > s.lastModified()) {
119 docstring const file = makeDisplayPath(s.absFilename(), 20);
120 docstring const text =
121 bformat(_("The backup of the document "
122 "%1$s is newer.\n\nLoad the "
123 "backup instead?"), file);
124 switch (Alert::prompt(_("Load backup?"), text, 0, 2,
125 _("&Load backup"), _("Load &original"),
129 // the file is not saved if we load the autosave file.
131 return b->readFile(a);
133 // Here we delete the autosave
140 return b->readFile(s);
148 bool loadLyXFile(Buffer * b, FileName const & s)
152 if (s.isReadable()) {
153 if (readFile(b, s)) {
154 b->lyxvc().file_found_hook(s);
156 b->setReadonly(true);
160 docstring const file = makeDisplayPath(s.absFilename(), 20);
161 // Here we probably should run
162 if (LyXVC::file_not_found_hook(s)) {
163 docstring const text =
164 bformat(_("Do you want to retrieve the document"
165 " %1$s from version control?"), file);
166 int const ret = Alert::prompt(_("Retrieve from version control?"),
167 text, 0, 1, _("&Retrieve"), _("&Cancel"));
170 // How can we know _how_ to do the checkout?
171 // With the current VC support it has to be,
172 // a RCS file since CVS do not have special ,v files.
174 return loadLyXFile(b, s);
182 bool checkIfLoaded(FileName const & fn)
184 return theBufferList().getBuffer(fn.absFilename());
188 Buffer * checkAndLoadLyXFile(FileName const & filename)
190 // File already open?
191 Buffer * checkBuffer = theBufferList().getBuffer(filename.absFilename());
193 if (checkBuffer->isClean())
195 docstring const file = makeDisplayPath(filename.absFilename(), 20);
196 docstring text = bformat(_(
197 "The document %1$s is already loaded and has unsaved changes.\n"
198 "Do you want to abandon your changes and reload the version on disk?"), file);
199 if (Alert::prompt(_("Reload saved document?"),
200 text, 0, 1, _("&Reload"), _("&Keep Changes")))
203 // FIXME: should be LFUN_REVERT
204 if (theBufferList().close(checkBuffer, false))
206 return checkAndLoadLyXFile(filename);
208 // The file could not be closed.
212 if (filename.isReadable()) {
213 Buffer * b = theBufferList().newBuffer(filename.absFilename());
214 if (!lyx::loadLyXFile(b, filename)) {
215 theBufferList().release(b);
221 docstring text = bformat(_("The document %1$s does not yet "
222 "exist.\n\nDo you want to create a new document?"),
223 from_utf8(filename.absFilename()));
224 if (!Alert::prompt(_("Create new document?"),
225 text, 0, 1, _("&Create"), _("Cancel")))
226 return newFile(filename.absFilename(), string(), true);
231 // FIXME newFile() should probably be a member method of Application...
232 Buffer * newFile(string const & filename, string const & templatename,
236 Buffer * b = theBufferList().newBuffer(filename);
240 // use defaults.lyx as a default template if it exists.
241 if (templatename.empty())
242 tname = libFileSearch("templates", "defaults.lyx");
244 tname = makeAbsPath(templatename);
246 if (!tname.empty()) {
247 if (!b->readFile(tname)) {
248 docstring const file = makeDisplayPath(tname.absFilename(), 50);
249 docstring const text = bformat(
250 _("The specified document template\n%1$s\ncould not be read."),
252 Alert::error(_("Could not read template"), text);
253 theBufferList().release(b);
260 b->setFileName(filename);
263 b->setReadonly(false);
264 b->fully_loaded(true);
270 void bufferErrors(Buffer const & buf, TeXErrors const & terr,
271 ErrorList & errorList)
273 TeXErrors::Errors::const_iterator cit = terr.begin();
274 TeXErrors::Errors::const_iterator end = terr.end();
276 for (; cit != end; ++cit) {
279 int errorrow = cit->error_in_line;
280 bool found = buf.texrow().getIdFromRow(errorrow, id_start,
286 found = buf.texrow().getIdFromRow(errorrow, id_end,
288 } while (found && id_start == id_end && pos_start == pos_end);
290 errorList.push_back(ErrorItem(cit->error_desc,
291 cit->error_text, id_start, pos_start, pos_end));
296 string const bufferFormat(Buffer const & buffer)
298 if (buffer.isDocBook())
300 else if (buffer.isLiterate())
307 int countWords(DocIterator const & from, DocIterator const & to)
311 for (DocIterator dit = from ; dit != to ; dit.forwardPos()) {
312 // Copied and adapted from isLetter() in ControlSpellChecker
314 && dit.pos() != dit.lastpos()
315 && dit.paragraph().isLetter(dit.pos())
316 && !dit.paragraph().isDeleted(dit.pos())) {
331 depth_type getDepth(DocIterator const & it)
333 depth_type depth = 0;
334 for (size_t i = 0 ; i < it.depth() ; ++i)
335 if (!it[i].inset().inMathed())
336 depth += it[i].paragraph().getDepth() + 1;
337 // remove 1 since the outer inset does not count
341 depth_type getItemDepth(ParIterator const & it)
343 Paragraph const & par = *it;
344 LabelType const labeltype = par.layout()->labeltype;
346 if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
349 // this will hold the lowest depth encountered up to now.
350 depth_type min_depth = getDepth(it);
351 ParIterator prev_it = it;
354 --prev_it.top().pit();
356 // start of nested inset: go to outer par
358 if (prev_it.empty()) {
359 // start of document: nothing to do
364 // We search for the first paragraph with same label
365 // that is not more deeply nested.
366 Paragraph & prev_par = *prev_it;
367 depth_type const prev_depth = getDepth(prev_it);
368 if (labeltype == prev_par.layout()->labeltype) {
369 if (prev_depth < min_depth) {
370 return prev_par.itemdepth + 1;
372 else if (prev_depth == min_depth) {
373 return prev_par.itemdepth;
376 min_depth = std::min(min_depth, prev_depth);
377 // small optimization: if we are at depth 0, we won't
378 // find anything else
379 if (prev_depth == 0) {
386 bool needEnumCounterReset(ParIterator const & it)
388 Paragraph const & par = *it;
389 BOOST_ASSERT(par.layout()->labeltype == LABEL_ENUMERATE);
390 depth_type const cur_depth = par.getDepth();
391 ParIterator prev_it = it;
392 while (prev_it.pit()) {
393 --prev_it.top().pit();
394 Paragraph const & prev_par = *prev_it;
395 if (prev_par.getDepth() <= cur_depth)
396 return prev_par.layout()->labeltype != LABEL_ENUMERATE;
398 // start of nested inset: reset
403 // set the label of a paragraph. This includes the counters.
404 void setLabel(Buffer const & buf, ParIterator & it)
406 TextClass const & textclass = buf.params().getTextClass();
407 Paragraph & par = it.paragraph();
408 LayoutPtr const & layout = par.layout();
409 Counters & counters = textclass.counters();
411 if (par.params().startOfAppendix()) {
412 // FIXME: only the counter corresponding to toplevel
413 // sectionning should be reset
415 counters.appendix(true);
417 par.params().appendix(counters.appendix());
419 // Compute the item depth of the paragraph
420 par.itemdepth = getItemDepth(it);
422 if (layout->margintype == MARGIN_MANUAL) {
423 if (par.params().labelWidthString().empty())
424 par.params().labelWidthString(par.translateIfPossible(layout->labelstring(), buf.params()));
426 par.params().labelWidthString(docstring());
429 switch(layout->labeltype) {
431 if (layout->toclevel <= buf.params().secnumdepth
432 && (layout->latextype != LATEX_ENVIRONMENT
433 || isFirstInSequence(it.pit(), it.plist()))) {
434 counters.step(layout->counter);
435 par.params().labelString(
436 par.expandLabel(layout, buf.params()));
438 par.params().labelString(docstring());
441 case LABEL_ITEMIZE: {
442 // At some point of time we should do something more
443 // clever here, like:
444 // par.params().labelString(
445 // buf.params().user_defined_bullet(par.itemdepth).getText());
446 // for now, use a simple hardcoded label
448 switch (par.itemdepth) {
450 itemlabel = char_type(0x2022);
453 itemlabel = char_type(0x2013);
456 itemlabel = char_type(0x2217);
459 itemlabel = char_type(0x2219); // or 0x00b7
462 par.params().labelString(itemlabel);
466 case LABEL_ENUMERATE: {
467 // FIXME: Yes I know this is a really, really! bad solution
469 docstring enumcounter = from_ascii("enum");
471 switch (par.itemdepth) {
483 // not a valid enumdepth...
487 // Maybe we have to reset the enumeration counter.
488 if (needEnumCounterReset(it))
489 counters.reset(enumcounter);
491 counters.step(enumcounter);
495 switch (par.itemdepth) {
497 format = N_("\\arabic{enumi}.");
500 format = N_("(\\alph{enumii})");
503 format = N_("\\roman{enumiii}.");
506 format = N_("\\Alph{enumiv}.");
509 // not a valid enumdepth...
513 par.params().labelString(counters.counterLabel(
514 par.translateIfPossible(from_ascii(format), buf.params())));
519 case LABEL_SENSITIVE: {
520 string const & type = counters.current_float();
521 docstring full_label;
523 full_label = buf.B_("Senseless!!! ");
525 docstring name = buf.B_(textclass.floats().getType(type).name());
526 if (counters.hasCounter(from_utf8(type))) {
527 counters.step(from_utf8(type));
528 full_label = bformat(from_ascii("%1$s %2$s:"),
530 counters.theCounter(from_utf8(type)));
532 full_label = bformat(from_ascii("%1$s #:"), name);
534 par.params().labelString(full_label);
539 par.params().labelString(docstring());
543 case LABEL_TOP_ENVIRONMENT:
544 case LABEL_CENTERED_TOP_ENVIRONMENT:
547 par.params().labelString(
548 par.translateIfPossible(layout->labelstring(),
556 void updateLabels(Buffer const & buf, ParIterator & parit)
558 BOOST_ASSERT(parit.pit() == 0);
560 depth_type maxdepth = 0;
561 pit_type const lastpit = parit.lastpit();
562 for ( ; parit.pit() <= lastpit ; ++parit.pit()) {
563 // reduce depth if necessary
564 parit->params().depth(min(parit->params().depth(), maxdepth));
565 maxdepth = parit->getMaxDepthAfter();
567 // set the counter for this paragraph
568 setLabel(buf, parit);
571 InsetList::const_iterator iit = parit->insetList().begin();
572 InsetList::const_iterator end = parit->insetList().end();
573 for (; iit != end; ++iit) {
574 parit.pos() = iit->pos;
575 iit->inset->updateLabels(buf, parit);
582 // FIXME: buf should should be const because updateLabels() modifies
583 // the contents of the paragraphs.
584 void updateLabels(Buffer const & buf, bool childonly)
586 Buffer const * const master = buf.getMasterBuffer();
587 // Use the master text class also for child documents
588 TextClass const & textclass = master->params().getTextClass();
591 // If this is a child document start with the master
592 if (master != &buf) {
593 updateLabels(*master);
597 // start over the counters
598 textclass.counters().reset();
601 Buffer & cbuf = const_cast<Buffer &>(buf);
603 if (buf.text().empty()) {
604 // FIXME: we don't call continue with updateLabels()
605 // here because it crashes on newly created documents.
606 // But the TocBackend needs to be initialised
607 // nonetheless so we update the tocBackend manually.
608 cbuf.tocBackend().update();
613 ParIterator parit = par_iterator_begin(buf.inset());
614 updateLabels(buf, parit);
616 cbuf.tocBackend().update();
618 cbuf.structureChanged();
620 // the embedding signal is emitted with structureChanged signal
621 // this is inaccurate so these two will be separated later.
622 //cbuf.embeddedFiles().update();
623 //cbuf.embeddingChanged();
627 void checkBufferStructure(Buffer & buffer, ParIterator const & par_it)
629 if (par_it->layout()->toclevel != Layout::NOT_IN_TOC) {
630 Buffer * master = buffer.getMasterBuffer();
631 master->tocBackend().updateItem(par_it);
632 master->structureChanged();
636 textclass_type defaultTextclass()
638 // We want to return the article class. if `first' is
639 // true in the returned pair, then `second' is the textclass
640 // number; if it is false, second is 0. In both cases, second
642 return textclasslist.numberOfClass("article").second;
646 void loadChildDocuments(Buffer const & buf)
648 bool parse_error = false;
650 for (InsetIterator it = inset_iterator_begin(buf.inset()); it; ++it) {
651 if (it->lyxCode() != INCLUDE_CODE)
653 InsetInclude const & inset = static_cast<InsetInclude const &>(*it);
654 InsetCommandParams const & ip = inset.params();
655 Buffer * child = loadIfNeeded(buf, ip);
658 parse_error |= !child->errorList("Parse").empty();
659 loadChildDocuments(*child);
662 if (use_gui && buf.getMasterBuffer() == &buf)