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 "InsetIterator.h"
30 #include "TextClass.h"
31 #include "TextClassList.h"
32 #include "Paragraph.h"
33 #include "paragraph_funcs.h"
34 #include "ParagraphList.h"
35 #include "ParagraphParameters.h"
36 #include "ParIterator.h"
40 #include "TocBackend.h"
41 #include "VCBackend.h"
43 #include "frontends/alert.h"
45 #include "insets/InsetBibitem.h"
46 #include "insets/InsetInclude.h"
48 #include "support/filetools.h"
49 #include "support/fs_extras.h"
50 #include "support/lyxlib.h"
52 #include <boost/bind.hpp>
53 #include <boost/filesystem/operations.hpp>
63 using support::bformat;
64 using support::FileName;
65 using support::libFileSearch;
66 using support::makeAbsPath;
67 using support::makeDisplayPath;
68 using support::onlyFilename;
69 using support::onlyPath;
70 using support::unlink;
72 namespace Alert = frontend::Alert;
73 namespace fs = boost::filesystem;
77 bool readFile(Buffer * const b, FileName const & s)
81 // File information about normal file
82 if (!fs::exists(s.toFilesystemEncoding())) {
83 docstring const file = makeDisplayPath(s.absFilename(), 50);
84 docstring text = bformat(_("The specified document\n%1$s"
85 "\ncould not be read."), file);
86 Alert::error(_("Could not read document"), text);
90 // Check if emergency save file exists and is newer.
91 FileName const e(s.absFilename() + ".emergency");
93 if (fs::exists(e.toFilesystemEncoding()) &&
94 fs::exists(s.toFilesystemEncoding()) &&
95 fs::last_write_time(e.toFilesystemEncoding()) > fs::last_write_time(s.toFilesystemEncoding()))
97 docstring const file = makeDisplayPath(s.absFilename(), 20);
98 docstring const text =
99 bformat(_("An emergency save of the document "
101 "Recover emergency save?"), file);
102 switch (Alert::prompt(_("Load emergency save?"), text, 0, 2,
103 _("&Recover"), _("&Load Original"),
107 // the file is not saved if we load the emergency file.
109 return b->readFile(e);
117 // Now check if autosave file is newer.
118 FileName const a(onlyPath(s.absFilename()) + '#' + onlyFilename(s.absFilename()) + '#');
120 if (fs::exists(a.toFilesystemEncoding()) &&
121 fs::exists(s.toFilesystemEncoding()) &&
122 fs::last_write_time(a.toFilesystemEncoding()) > fs::last_write_time(s.toFilesystemEncoding()))
124 docstring const file = makeDisplayPath(s.absFilename(), 20);
125 docstring const text =
126 bformat(_("The backup of the document "
127 "%1$s is newer.\n\nLoad the "
128 "backup instead?"), file);
129 switch (Alert::prompt(_("Load backup?"), text, 0, 2,
130 _("&Load backup"), _("Load &original"),
134 // the file is not saved if we load the autosave file.
136 return b->readFile(a);
138 // Here we delete the autosave
145 return b->readFile(s);
153 bool loadLyXFile(Buffer * b, FileName const & s)
157 if (fs::is_readable(s.toFilesystemEncoding())) {
158 if (readFile(b, s)) {
159 b->lyxvc().file_found_hook(s);
160 if (!fs::is_writable(s.toFilesystemEncoding()))
161 b->setReadonly(true);
165 docstring const file = makeDisplayPath(s.absFilename(), 20);
166 // Here we probably should run
167 if (LyXVC::file_not_found_hook(s)) {
168 docstring const text =
169 bformat(_("Do you want to retrieve the document"
170 " %1$s from version control?"), file);
171 int const ret = Alert::prompt(_("Retrieve from version control?"),
172 text, 0, 1, _("&Retrieve"), _("&Cancel"));
175 // How can we know _how_ to do the checkout?
176 // With the current VC support it has to be,
177 // a RCS file since CVS do not have special ,v files.
179 return loadLyXFile(b, s);
187 bool checkIfLoaded(FileName const & fn)
189 return theBufferList().getBuffer(fn.absFilename());
193 Buffer * checkAndLoadLyXFile(FileName const & filename)
195 // File already open?
196 Buffer * checkBuffer = theBufferList().getBuffer(filename.absFilename());
198 if (checkBuffer->isClean())
200 docstring const file = makeDisplayPath(filename.absFilename(), 20);
201 docstring text = bformat(_(
202 "The document %1$s is already loaded and has unsaved changes.\n"
203 "Do you want to abandon your changes and reload the version on disk?"), file);
204 if (Alert::prompt(_("Reload saved document?"),
205 text, 0, 1, _("&Reload"), _("&Keep Changes")))
208 // FIXME: should be LFUN_REVERT
209 if (theBufferList().close(checkBuffer, false))
211 return checkAndLoadLyXFile(filename);
213 // The file could not be closed.
217 if (isFileReadable(filename)) {
218 Buffer * b = theBufferList().newBuffer(filename.absFilename());
219 if (!lyx::loadLyXFile(b, filename)) {
220 theBufferList().release(b);
226 docstring text = bformat(_("The document %1$s does not yet "
227 "exist.\n\nDo you want to create a new document?"),
228 from_utf8(filename.absFilename()));
229 if (!Alert::prompt(_("Create new document?"),
230 text, 0, 1, _("&Create"), _("Cancel")))
231 return newFile(filename.absFilename(), string(), true);
236 // FIXME newFile() should probably be a member method of Application...
237 Buffer * newFile(string const & filename, string const & templatename,
241 Buffer * b = theBufferList().newBuffer(filename);
245 // use defaults.lyx as a default template if it exists.
246 if (templatename.empty())
247 tname = libFileSearch("templates", "defaults.lyx");
249 tname = makeAbsPath(templatename);
251 if (!tname.empty()) {
252 if (!b->readFile(tname)) {
253 docstring const file = makeDisplayPath(tname.absFilename(), 50);
254 docstring const text = bformat(
255 _("The specified document template\n%1$s\ncould not be read."),
257 Alert::error(_("Could not read template"), text);
258 theBufferList().release(b);
265 b->setFileName(filename);
268 b->setReadonly(false);
269 b->fully_loaded(true);
275 void bufferErrors(Buffer const & buf, TeXErrors const & terr,
276 ErrorList & errorList)
278 TeXErrors::Errors::const_iterator cit = terr.begin();
279 TeXErrors::Errors::const_iterator end = terr.end();
281 for (; cit != end; ++cit) {
284 int errorrow = cit->error_in_line;
285 bool found = buf.texrow().getIdFromRow(errorrow, id_start,
291 found = buf.texrow().getIdFromRow(errorrow, id_end,
293 } while (found && id_start == id_end && pos_start == pos_end);
295 errorList.push_back(ErrorItem(cit->error_desc,
296 cit->error_text, id_start, pos_start, pos_end));
301 string const bufferFormat(Buffer const & buffer)
303 if (buffer.isDocBook())
305 else if (buffer.isLiterate())
312 int countWords(DocIterator const & from, DocIterator const & to)
316 for (DocIterator dit = from ; dit != to ; dit.forwardPos()) {
317 // Copied and adapted from isLetter() in ControlSpellChecker
319 && dit.pos() != dit.lastpos()
320 && dit.paragraph().isLetter(dit.pos())
321 && !dit.paragraph().isDeleted(dit.pos())) {
336 depth_type getDepth(DocIterator const & it)
338 depth_type depth = 0;
339 for (size_t i = 0 ; i < it.depth() ; ++i)
340 if (!it[i].inset().inMathed())
341 depth += it[i].paragraph().getDepth() + 1;
342 // remove 1 since the outer inset does not count
346 depth_type getItemDepth(ParIterator const & it)
348 Paragraph const & par = *it;
349 LYX_LABEL_TYPES const labeltype = par.layout()->labeltype;
351 if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
354 // this will hold the lowest depth encountered up to now.
355 depth_type min_depth = getDepth(it);
356 ParIterator prev_it = it;
359 --prev_it.top().pit();
361 // start of nested inset: go to outer par
363 if (prev_it.empty()) {
364 // start of document: nothing to do
369 // We search for the first paragraph with same label
370 // that is not more deeply nested.
371 Paragraph & prev_par = *prev_it;
372 depth_type const prev_depth = getDepth(prev_it);
373 if (labeltype == prev_par.layout()->labeltype) {
374 if (prev_depth < min_depth) {
375 return prev_par.itemdepth + 1;
377 else if (prev_depth == min_depth) {
378 return prev_par.itemdepth;
381 min_depth = std::min(min_depth, prev_depth);
382 // small optimization: if we are at depth 0, we won't
383 // find anything else
384 if (prev_depth == 0) {
391 bool needEnumCounterReset(ParIterator const & it)
393 Paragraph const & par = *it;
394 BOOST_ASSERT(par.layout()->labeltype == LABEL_ENUMERATE);
395 depth_type const cur_depth = par.getDepth();
396 ParIterator prev_it = it;
397 while (prev_it.pit()) {
398 --prev_it.top().pit();
399 Paragraph const & prev_par = *prev_it;
400 if (prev_par.getDepth() <= cur_depth)
401 return prev_par.layout()->labeltype != LABEL_ENUMERATE;
403 // start of nested inset: reset
408 // set the label of a paragraph. This includes the counters.
409 void setLabel(Buffer const & buf, ParIterator & it)
411 TextClass const & textclass = buf.params().getTextClass();
412 Paragraph & par = it.paragraph();
413 LayoutPtr const & layout = par.layout();
414 Counters & counters = textclass.counters();
416 if (par.params().startOfAppendix()) {
417 // FIXME: only the counter corresponding to toplevel
418 // sectionning should be reset
420 counters.appendix(true);
422 par.params().appendix(counters.appendix());
424 // Compute the item depth of the paragraph
425 par.itemdepth = getItemDepth(it);
427 if (layout->margintype == MARGIN_MANUAL) {
428 if (par.params().labelWidthString().empty())
429 par.params().labelWidthString(par.translateIfPossible(layout->labelstring(), buf.params()));
431 par.params().labelWidthString(docstring());
434 switch(layout->labeltype) {
436 if (layout->toclevel <= buf.params().secnumdepth
437 && (layout->latextype != LATEX_ENVIRONMENT
438 || isFirstInSequence(it.pit(), it.plist()))) {
439 counters.step(layout->counter);
440 par.params().labelString(
441 par.expandLabel(layout, buf.params()));
443 par.params().labelString(docstring());
446 case LABEL_ITEMIZE: {
447 // At some point of time we should do something more
448 // clever here, like:
449 // par.params().labelString(
450 // buf.params().user_defined_bullet(par.itemdepth).getText());
451 // for now, use a simple hardcoded label
453 switch (par.itemdepth) {
455 itemlabel = char_type(0x2022);
458 itemlabel = char_type(0x2013);
461 itemlabel = char_type(0x2217);
464 itemlabel = char_type(0x2219); // or 0x00b7
467 par.params().labelString(itemlabel);
471 case LABEL_ENUMERATE: {
472 // FIXME: Yes I know this is a really, really! bad solution
474 docstring enumcounter = from_ascii("enum");
476 switch (par.itemdepth) {
488 // not a valid enumdepth...
492 // Maybe we have to reset the enumeration counter.
493 if (needEnumCounterReset(it))
494 counters.reset(enumcounter);
496 counters.step(enumcounter);
500 switch (par.itemdepth) {
502 format = N_("\\arabic{enumi}.");
505 format = N_("(\\alph{enumii})");
508 format = N_("\\roman{enumiii}.");
511 format = N_("\\Alph{enumiv}.");
514 // not a valid enumdepth...
518 par.params().labelString(counters.counterLabel(
519 par.translateIfPossible(from_ascii(format), buf.params())));
524 case LABEL_SENSITIVE: {
525 string const & type = counters.current_float();
526 docstring full_label;
528 full_label = buf.B_("Senseless!!! ");
530 docstring name = buf.B_(textclass.floats().getType(type).name());
531 if (counters.hasCounter(from_utf8(type))) {
532 counters.step(from_utf8(type));
533 full_label = bformat(from_ascii("%1$s %2$s:"),
535 counters.theCounter(from_utf8(type)));
537 full_label = bformat(from_ascii("%1$s #:"), name);
539 par.params().labelString(full_label);
544 par.params().labelString(docstring());
548 case LABEL_TOP_ENVIRONMENT:
549 case LABEL_CENTERED_TOP_ENVIRONMENT:
552 par.params().labelString(
553 par.translateIfPossible(layout->labelstring(),
561 void updateLabels(Buffer const & buf, ParIterator & parit)
563 BOOST_ASSERT(parit.pit() == 0);
565 depth_type maxdepth = 0;
566 pit_type const lastpit = parit.lastpit();
567 for ( ; parit.pit() <= lastpit ; ++parit.pit()) {
568 // reduce depth if necessary
569 parit->params().depth(min(parit->params().depth(), maxdepth));
570 maxdepth = parit->getMaxDepthAfter();
572 // set the counter for this paragraph
573 setLabel(buf, parit);
576 InsetList::const_iterator iit = parit->insetlist.begin();
577 InsetList::const_iterator end = parit->insetlist.end();
578 for (; iit != end; ++iit) {
579 parit.pos() = iit->pos;
580 iit->inset->updateLabels(buf, parit);
587 // FIXME: buf should should be const because updateLabels() modifies
588 // the contents of the paragraphs.
589 void updateLabels(Buffer const & buf, bool childonly)
591 Buffer const * const master = buf.getMasterBuffer();
592 // Use the master text class also for child documents
593 TextClass const & textclass = master->params().getTextClass();
596 // If this is a child document start with the master
597 if (master != &buf) {
598 updateLabels(*master);
602 // start over the counters
603 textclass.counters().reset();
606 Buffer & cbuf = const_cast<Buffer &>(buf);
608 if (buf.text().empty()) {
609 // FIXME: we don't call continue with updateLabels()
610 // here because it crashes on newly created documents.
611 // But the TocBackend needs to be initialised
612 // nonetheless so we update the tocBackend manually.
613 cbuf.tocBackend().update();
618 ParIterator parit = par_iterator_begin(buf.inset());
619 updateLabels(buf, parit);
621 cbuf.tocBackend().update();
623 cbuf.structureChanged();
625 // the embedding signal is emitted with structureChanged signal
626 // this is inaccurate so these two will be separated later.
627 cbuf.embeddedFiles().update();
628 cbuf.embeddingChanged();
632 void checkBufferStructure(Buffer & buffer, ParIterator const & par_it)
634 if (par_it->layout()->toclevel != Layout::NOT_IN_TOC) {
635 Buffer * master = buffer.getMasterBuffer();
636 master->tocBackend().updateItem(par_it);
637 master->structureChanged();
641 textclass_type defaultTextclass()
643 // We want to return the article class. if `first' is
644 // true in the returned pair, then `second' is the textclass
645 // number; if it is false, second is 0. In both cases, second
647 return textclasslist.numberOfClass("article").second;
651 void loadChildDocuments(Buffer const & buf)
653 bool parse_error = false;
655 for (InsetIterator it = inset_iterator_begin(buf.inset()); it; ++it) {
656 if (it->lyxCode() != Inset::INCLUDE_CODE)
658 InsetInclude const & inset = static_cast<InsetInclude const &>(*it);
659 InsetCommandParams const & ip = inset.params();
660 Buffer * child = loadIfNeeded(buf, ip);
663 parse_error |= !child->errorList("Parse").empty();
664 loadChildDocuments(*child);
667 if (use_gui && buf.getMasterBuffer() == &buf)