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"
19 #include "dociterator.h"
21 #include "errorlist.h"
23 #include "FloatList.h"
27 #include "lyxtextclass.h"
28 #include "paragraph.h"
29 #include "paragraph_funcs.h"
30 #include "ParagraphList.h"
31 #include "ParagraphParameters.h"
32 #include "pariterator.h"
35 #include "vc-backend.h"
37 #include "frontends/Alert.h"
39 #include "insets/insetbibitem.h"
41 #include "support/filetools.h"
42 #include "support/fs_extras.h"
43 #include "support/lyxlib.h"
47 #include <boost/bind.hpp>
48 #include <boost/filesystem/operations.hpp>
53 using lyx::support::bformat;
54 using lyx::support::libFileSearch;
55 using lyx::support::makeDisplayPath;
56 using lyx::support::onlyFilename;
57 using lyx::support::onlyPath;
58 using lyx::support::unlink;
63 namespace fs = boost::filesystem;
65 extern BufferList bufferlist;
69 bool readFile(Buffer * const b, string const & s)
73 // File information about normal file
75 string const file = makeDisplayPath(s, 50);
76 string text = bformat(_("The specified document\n%1$s"
77 "\ncould not be read."), file);
78 Alert::error(_("Could not read document"), text);
82 // Check if emergency save file exists and is newer.
83 string const e = onlyPath(s) + onlyFilename(s) + ".emergency";
85 if (fs::exists(e) && fs::exists(s)
86 && fs::last_write_time(e) > fs::last_write_time(s))
88 string const file = makeDisplayPath(s, 20);
90 bformat(_("An emergency save of the document "
92 "Recover emergency save?"), file);
93 switch (Alert::prompt(_("Load emergency save?"), text, 0, 2,
94 _("&Recover"), _("&Load Original"),
98 // the file is not saved if we load the emergency file.
100 return b->readFile(e);
108 // Now check if autosave file is newer.
109 string const a = onlyPath(s) + '#' + onlyFilename(s) + '#';
111 if (fs::exists(a) && fs::exists(s)
112 && fs::last_write_time(a) > fs::last_write_time(s))
114 string const file = makeDisplayPath(s, 20);
116 bformat(_("The backup of the document "
117 "%1$s is newer.\n\nLoad the "
118 "backup instead?"), file);
119 switch (Alert::prompt(_("Load backup?"), text, 0, 2,
120 _("&Load backup"), _("Load &original"),
124 // the file is not saved if we load the autosave file.
126 return b->readFile(a);
128 // Here we delete the autosave
135 return b->readFile(s);
143 bool loadLyXFile(Buffer * b, string const & s)
147 if (fs::is_readable(s)) {
148 if (readFile(b, s)) {
149 b->lyxvc().file_found_hook(s);
150 if (!fs::is_writable(s))
151 b->setReadonly(true);
155 string const file = makeDisplayPath(s, 20);
156 // Here we probably should run
157 if (LyXVC::file_not_found_hook(s)) {
159 bformat(_("Do you want to retrieve the document"
160 " %1$s from version control?"), file);
161 int const ret = Alert::prompt(_("Retrieve from version control?"),
162 text, 0, 1, _("&Retrieve"), _("&Cancel"));
165 // How can we know _how_ to do the checkout?
166 // With the current VC support it has to be,
167 // a RCS file since CVS do not have special ,v files.
169 return loadLyXFile(b, s);
177 Buffer * newFile(string const & filename, string const & templatename,
181 Buffer * b = bufferlist.newBuffer(filename);
185 // use defaults.lyx as a default template if it exists.
186 if (templatename.empty())
187 tname = libFileSearch("templates", "defaults.lyx");
189 tname = templatename;
191 if (!tname.empty()) {
192 if (!b->readFile(tname)) {
193 string const file = makeDisplayPath(tname, 50);
194 string const text = bformat(_("The specified document template\n%1$s\ncould not be read."), file);
195 Alert::error(_("Could not read template"), text);
196 // no template, start with empty buffer
202 b->setFileName(filename);
205 b->setReadonly(false);
206 b->fully_loaded(true);
207 b->updateDocLang(b->params().language);
213 void bufferErrors(Buffer const & buf, TeXErrors const & terr)
215 TeXErrors::Errors::const_iterator cit = terr.begin();
216 TeXErrors::Errors::const_iterator end = terr.end();
218 for (; cit != end; ++cit) {
221 int errorrow = cit->error_in_line;
222 bool found = buf.texrow().getIdFromRow(errorrow, id_start,
228 found = buf.texrow().getIdFromRow(errorrow, id_end,
230 } while (found && id_start == id_end && pos_start == pos_end);
232 buf.error(ErrorItem(cit->error_desc, cit->error_text,
233 id_start, pos_start, pos_end));
238 void bufferErrors(Buffer const & buf, ErrorList const & el)
240 for_each(el.begin(), el.end(), bind(ref(buf.error), _1));
244 string const bufferFormat(Buffer const & buffer)
246 if (buffer.isLinuxDoc())
248 else if (buffer.isDocBook())
250 else if (buffer.isLiterate())
257 int countWords(DocIterator const & from, DocIterator const & to)
261 for (DocIterator dit = from ; dit != to ; dit.forwardPos()) {
262 // Copied and adapted from isLetter() in ControlSpellChecker
264 && dit.pos() != dit.lastpos()
265 && dit.paragraph().isLetter(dit.pos())
266 && !isDeletedText(dit.paragraph(), dit.pos())) {
281 lyx::depth_type getDepth(DocIterator const & it)
283 lyx::depth_type depth = 0;
284 for (size_t i = 0 ; i < it.depth() ; ++i)
285 if (!it[i].inset().inMathed())
286 depth += it[i].paragraph().getDepth() + 1;
287 // remove 1 since the outer inset does not count
291 lyx::depth_type getItemDepth(ParIterator const & it)
293 Paragraph const & par = *it;
294 LYX_LABEL_TYPES const labeltype = par.layout()->labeltype;
296 if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
299 // this will hold the lowest depth encountered up to now.
300 lyx::depth_type min_depth = getDepth(it);
301 ParIterator prev_it = it;
304 --prev_it.top().pit();
306 // start of nested inset: go to outer par
308 if (prev_it.empty()) {
309 // start of document: nothing to do
314 // We search for the first paragraph with same label
315 // that is not more deeply nested.
316 Paragraph & prev_par = *prev_it;
317 lyx::depth_type const prev_depth = getDepth(prev_it);
318 if (labeltype == prev_par.layout()->labeltype) {
319 if (prev_depth < min_depth) {
320 return prev_par.itemdepth + 1;
322 else if (prev_depth == min_depth) {
323 return prev_par.itemdepth;
326 min_depth = std::min(min_depth, prev_depth);
327 // small optimization: if we are at depth 0, we won't
328 // find anything else
329 if (prev_depth == 0) {
336 bool needEnumCounterReset(ParIterator const & it)
338 Paragraph const & par = *it;
339 BOOST_ASSERT(par.layout()->labeltype == LABEL_ENUMERATE);
340 lyx::depth_type const cur_depth = par.getDepth();
341 ParIterator prev_it = it;
342 while (prev_it.pit()) {
343 --prev_it.top().pit();
344 Paragraph const & prev_par = *prev_it;
345 if (prev_par.getDepth() <= cur_depth)
346 return prev_par.layout()->labeltype != LABEL_ENUMERATE;
348 // start of nested inset: reset
353 // set the label of a paragraph. This includes the counters.
354 void setLabel(Buffer const & buf, ParIterator & it)
356 Paragraph & par = *it;
357 BufferParams const & bufparams = buf.params();
358 LyXTextClass const & textclass = bufparams.getLyXTextClass();
359 LyXLayout_ptr const & layout = par.layout();
360 Counters & counters = textclass.counters();
363 par.params().appendix(par.params().startOfAppendix());
365 par.params().appendix(it.plist()[it.pit() - 1].params().appendix());
366 if (!par.params().appendix() &&
367 par.params().startOfAppendix()) {
368 par.params().appendix(true);
369 textclass.counters().reset();
373 // Compute the item depth of the paragraph
374 par.itemdepth = getItemDepth(it);
376 // erase what was there before
377 par.params().labelString(string());
379 if (layout->margintype == MARGIN_MANUAL) {
380 if (par.params().labelWidthString().empty())
381 par.setLabelWidthString(layout->labelstring());
383 par.setLabelWidthString(string());
386 // is it a layout that has an automatic label?
387 if (layout->labeltype == LABEL_COUNTER) {
388 if (layout->toclevel <= buf.params().secnumdepth
389 && (layout->latextype != LATEX_ENVIRONMENT
390 || isFirstInSequence(it.pit(), it.plist()))) {
391 counters.step(layout->counter);
392 string label = expandLabel(buf, layout,
393 par.params().appendix());
394 par.params().labelString(label);
396 } else if (layout->labeltype == LABEL_ITEMIZE) {
397 // At some point of time we should do something more
398 // clever here, like:
399 // par.params().labelString(
400 // bufparams.user_defined_bullet(par.itemdepth).getText());
401 // for now, use a simple hardcoded label
403 switch (par.itemdepth) {
418 par.params().labelString(itemlabel);
419 } else if (layout->labeltype == LABEL_ENUMERATE) {
421 // Yes I know this is a really, really! bad solution
423 string enumcounter = "enum";
425 switch (par.itemdepth) {
437 // not a valid enumdepth...
441 // Maybe we have to reset the enumeration counter.
442 if (needEnumCounterReset(it))
443 counters.reset(enumcounter);
445 counters.step(enumcounter);
449 switch (par.itemdepth) {
451 format = N_("\\arabic{enumi}.");
454 format = N_("(\\alph{enumii})");
457 format = N_("\\roman{enumiii}.");
460 format = N_("\\Alph{enumiv}.");
463 // not a valid enumdepth...
467 par.params().labelString(counters.counterLabel(buf.B_(format)));
468 } else if (layout->labeltype == LABEL_BIBLIO) {// ale970302
469 counters.step("bibitem");
470 int number = counters.value("bibitem");
472 par.bibitem()->setCounter(number);
473 par.params().labelString(buf.B_(layout->labelstring()));
474 // In biblio should't be following counters but...
475 } else if (layout->labeltype == LABEL_SENSITIVE) {
476 // Search for the first float or wrap inset in the iterator
478 size_t i = it.depth();
481 InsetBase * const in = &it[i].inset();
482 if (in->lyxCode() == InsetBase::FLOAT_CODE
483 || in->lyxCode() == InsetBase::WRAP_CODE) {
484 type = in->getInsetName();
491 Floating const & fl = textclass.floats().getType(type);
493 counters.step(fl.type());
495 // Doesn't work... yet.
496 s = bformat(_("%1$s #:"), buf.B_(fl.name()));
498 // par->SetLayout(0);
499 s = buf.B_(layout->labelstring());
502 par.params().labelString(s);
503 } else if (layout->labeltype == LABEL_NO_LABEL)
504 par.params().labelString(string());
506 par.params().labelString(buf.B_(layout->labelstring()));
512 bool updateCurrentLabel(Buffer const & buf,
515 if (it == par_iterator_end(buf.inset()))
518 switch (it->layout()->labeltype) {
523 case LABEL_TOP_ENVIRONMENT:
524 case LABEL_CENTERED_TOP_ENVIRONMENT:
530 case LABEL_SENSITIVE:
532 // do more things with enumerate later
533 case LABEL_ENUMERATE:
537 // This is dead code which get rid of a warning:
542 void updateLabels(Buffer const & buf,
543 ParIterator & from, ParIterator & to)
545 for (ParIterator it = from; it != to; ++it) {
546 if (it.pit() > it.lastpit())
548 if (!updateCurrentLabel (buf, it)) {
556 void updateLabels(Buffer const & buf,
559 if (updateCurrentLabel(buf, iter))
566 void updateLabels(Buffer const & buf)
568 // start over the counters
569 buf.params().getLyXTextClass().counters().reset();
571 ParIterator const end = par_iterator_end(buf.inset());
573 for (ParIterator it = par_iterator_begin(buf.inset()); it != end; ++it) {
574 // reduce depth if necessary
576 Paragraph const & prevpar = it.plist()[it.pit() - 1];
577 it->params().depth(min(it->params().depth(),
578 prevpar.getMaxDepthAfter()));
580 it->params().depth(0);
582 // set the counter for this paragraph
588 string expandLabel(Buffer const & buf,
589 LyXLayout_ptr const & layout, bool appendix)
591 LyXTextClass const & tclass = buf.params().getLyXTextClass();
593 string fmt = buf.B_(appendix ? layout->labelstring_appendix()
594 : layout->labelstring());
596 // handle 'inherited level parts' in 'fmt',
597 // i.e. the stuff between '@' in '@Section@.\arabic{subsection}'
598 size_t const i = fmt.find('@', 0);
599 if (i != string::npos) {
600 size_t const j = fmt.find('@', i + 1);
601 if (j != string::npos) {
602 string parent(fmt, i + 1, j - i - 1);
603 string label = expandLabel(buf, tclass[parent], appendix);
604 fmt = string(fmt, 0, i) + label + string(fmt, j + 1, string::npos);
608 return tclass.counters().counterLabel(fmt);