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"
19 #include "DocIterator.h"
21 #include "ErrorList.h"
23 #include "FloatList.h"
24 #include "InsetList.h"
25 #include "InsetIterator.h"
29 #include "LayoutPtr.h"
31 #include "TextClass.h"
32 #include "Paragraph.h"
33 #include "paragraph_funcs.h"
34 #include "ParagraphList.h"
35 #include "ParagraphParameters.h"
36 #include "ParIterator.h"
39 #include "TocBackend.h"
41 #include "frontends/alert.h"
43 #include "insets/InsetBibitem.h"
44 #include "insets/InsetInclude.h"
46 #include "support/convert.h"
47 #include "support/debug.h"
48 #include "support/filetools.h"
49 #include "support/gettext.h"
50 #include "support/lstrings.h"
51 #include "support/textutils.h"
54 using namespace lyx::support;
58 namespace Alert = frontend::Alert;
61 Buffer * checkAndLoadLyXFile(FileName const & filename)
64 Buffer * checkBuffer = theBufferList().getBuffer(filename.absFilename());
66 if (checkBuffer->isClean())
68 docstring const file = makeDisplayPath(filename.absFilename(), 20);
69 docstring text = bformat(_(
70 "The document %1$s is already loaded and has unsaved changes.\n"
71 "Do you want to abandon your changes and reload the version on disk?"), file);
72 if (Alert::prompt(_("Reload saved document?"),
73 text, 0, 1, _("&Reload"), _("&Keep Changes")))
76 // FIXME: should be LFUN_REVERT
77 theBufferList().release(checkBuffer);
79 return checkAndLoadLyXFile(filename);
82 if (filename.exists()) {
83 if (!filename.isReadableFile()) {
84 docstring text = bformat(_("The file %1$s exists but is not "
85 "readable by the current user."),
86 from_utf8(filename.absFilename()));
87 Alert::error(_("File not readable!"), text);
90 Buffer * b = theBufferList().newBuffer(filename.absFilename());
92 // Buffer creation is not possible.
94 if (!b->loadLyXFile(filename)) {
95 theBufferList().release(b);
101 docstring text = bformat(_("The document %1$s does not yet "
102 "exist.\n\nDo you want to create a new document?"),
103 from_utf8(filename.absFilename()));
104 if (!Alert::prompt(_("Create new document?"),
105 text, 0, 1, _("&Create"), _("Cancel")))
106 return newFile(filename.absFilename(), string(), true);
112 // FIXME newFile() should probably be a member method of Application...
113 Buffer * newFile(string const & filename, string const & templatename,
117 Buffer * b = theBufferList().newBuffer(filename);
119 // Buffer creation is not possible.
123 // use defaults.lyx as a default template if it exists.
124 if (templatename.empty())
125 tname = libFileSearch("templates", "defaults.lyx");
127 tname = makeAbsPath(templatename);
129 if (!tname.empty()) {
130 if (!b->readFile(tname)) {
131 docstring const file = makeDisplayPath(tname.absFilename(), 50);
132 docstring const text = bformat(
133 _("The specified document template\n%1$s\ncould not be read."),
135 Alert::error(_("Could not read template"), text);
136 theBufferList().release(b);
143 b->setFileName(filename);
146 b->setReadonly(false);
147 b->setFullyLoaded(true);
153 Buffer * newUnnamedFile(string const & templatename, FileName const & path)
155 static int newfile_number;
157 string document_path = path.absFilename();
158 string filename = addName(document_path,
159 "newfile" + convert<string>(++newfile_number) + ".lyx");
160 while (theBufferList().exists(filename)
161 || FileName(filename).isReadableFile()) {
163 filename = addName(document_path,
164 "newfile" + convert<string>(newfile_number) + ".lyx");
166 return newFile(filename, templatename, false);
170 int countWords(DocIterator const & from, DocIterator const & to)
174 for (DocIterator dit = from ; dit != to ; dit.forwardPos()) {
175 // Copied and adapted from isLetter() in ControlSpellChecker
177 && dit.pos() != dit.lastpos()
178 && dit.paragraph().isLetter(dit.pos())
179 && !dit.paragraph().isDeleted(dit.pos())) {
192 int countChars(DocIterator const & from, DocIterator const & to, bool with_blanks)
196 for (DocIterator dit = from ; dit != to ; dit.forwardPos()) {
198 if (!dit.inTexted()) continue;
199 Paragraph const & par = dit.paragraph();
200 pos_type const pos = dit.pos();
202 if (pos != dit.lastpos() && !par.isDeleted(pos)) {
203 if (Inset const * ins = par.getInset(pos)) {
206 else if (with_blanks && ins->isSpace())
209 char_type const c = par.getChar(pos);
210 if (isPrintableNonspace(c))
212 else if (isSpace(c) && with_blanks)
218 return chars + blanks;
224 depth_type getDepth(DocIterator const & it)
226 depth_type depth = 0;
227 for (size_t i = 0 ; i < it.depth() ; ++i)
228 if (!it[i].inset().inMathed())
229 depth += it[i].paragraph().getDepth() + 1;
230 // remove 1 since the outer inset does not count
234 depth_type getItemDepth(ParIterator const & it)
236 Paragraph const & par = *it;
237 LabelType const labeltype = par.layout()->labeltype;
239 if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
242 // this will hold the lowest depth encountered up to now.
243 depth_type min_depth = getDepth(it);
244 ParIterator prev_it = it;
247 --prev_it.top().pit();
249 // start of nested inset: go to outer par
251 if (prev_it.empty()) {
252 // start of document: nothing to do
257 // We search for the first paragraph with same label
258 // that is not more deeply nested.
259 Paragraph & prev_par = *prev_it;
260 depth_type const prev_depth = getDepth(prev_it);
261 if (labeltype == prev_par.layout()->labeltype) {
262 if (prev_depth < min_depth)
263 return prev_par.itemdepth + 1;
264 if (prev_depth == min_depth)
265 return prev_par.itemdepth;
267 min_depth = min(min_depth, prev_depth);
268 // small optimization: if we are at depth 0, we won't
269 // find anything else
276 bool needEnumCounterReset(ParIterator const & it)
278 Paragraph const & par = *it;
279 BOOST_ASSERT(par.layout()->labeltype == LABEL_ENUMERATE);
280 depth_type const cur_depth = par.getDepth();
281 ParIterator prev_it = it;
282 while (prev_it.pit()) {
283 --prev_it.top().pit();
284 Paragraph const & prev_par = *prev_it;
285 if (prev_par.getDepth() <= cur_depth)
286 return prev_par.layout()->labeltype != LABEL_ENUMERATE;
288 // start of nested inset: reset
293 // set the label of a paragraph. This includes the counters.
294 void setLabel(Buffer const & buf, ParIterator & it)
296 DocumentClass const & textclass = buf.params().documentClass();
297 Paragraph & par = it.paragraph();
298 LayoutPtr const & layout = par.layout();
299 Counters & counters = textclass.counters();
301 if (par.params().startOfAppendix()) {
302 // FIXME: only the counter corresponding to toplevel
303 // sectionning should be reset
305 counters.appendix(true);
307 par.params().appendix(counters.appendix());
309 // Compute the item depth of the paragraph
310 par.itemdepth = getItemDepth(it);
312 if (layout->margintype == MARGIN_MANUAL) {
313 if (par.params().labelWidthString().empty())
314 par.params().labelWidthString(par.translateIfPossible(layout->labelstring(), buf.params()));
316 par.params().labelWidthString(docstring());
319 switch(layout->labeltype) {
321 if (layout->toclevel <= buf.params().secnumdepth
322 && (layout->latextype != LATEX_ENVIRONMENT
323 || isFirstInSequence(it.pit(), it.plist()))) {
324 counters.step(layout->counter);
325 par.params().labelString(
326 par.expandLabel(layout, buf.params()));
328 par.params().labelString(docstring());
331 case LABEL_ITEMIZE: {
332 // At some point of time we should do something more
333 // clever here, like:
334 // par.params().labelString(
335 // buf.params().user_defined_bullet(par.itemdepth).getText());
336 // for now, use a simple hardcoded label
338 switch (par.itemdepth) {
340 itemlabel = char_type(0x2022);
343 itemlabel = char_type(0x2013);
346 itemlabel = char_type(0x2217);
349 itemlabel = char_type(0x2219); // or 0x00b7
352 par.params().labelString(itemlabel);
356 case LABEL_ENUMERATE: {
357 // FIXME: Yes I know this is a really, really! bad solution
359 docstring enumcounter = from_ascii("enum");
361 switch (par.itemdepth) {
373 // not a valid enumdepth...
377 // Maybe we have to reset the enumeration counter.
378 if (needEnumCounterReset(it))
379 counters.reset(enumcounter);
381 counters.step(enumcounter);
385 switch (par.itemdepth) {
387 format = N_("\\arabic{enumi}.");
390 format = N_("(\\alph{enumii})");
393 format = N_("\\roman{enumiii}.");
396 format = N_("\\Alph{enumiv}.");
399 // not a valid enumdepth...
403 par.params().labelString(counters.counterLabel(
404 par.translateIfPossible(from_ascii(format), buf.params())));
409 case LABEL_SENSITIVE: {
410 string const & type = counters.current_float();
411 docstring full_label;
413 full_label = buf.B_("Senseless!!! ");
415 docstring name = buf.B_(textclass.floats().getType(type).name());
416 if (counters.hasCounter(from_utf8(type))) {
417 counters.step(from_utf8(type));
418 full_label = bformat(from_ascii("%1$s %2$s:"),
420 counters.theCounter(from_utf8(type)));
422 full_label = bformat(from_ascii("%1$s #:"), name);
424 par.params().labelString(full_label);
429 par.params().labelString(docstring());
433 case LABEL_TOP_ENVIRONMENT:
434 case LABEL_CENTERED_TOP_ENVIRONMENT:
437 par.params().labelString(
438 par.translateIfPossible(layout->labelstring(),
446 void updateLabels(Buffer const & buf, ParIterator & parit)
448 BOOST_ASSERT(parit.pit() == 0);
450 // set the position of the text in the buffer to be able
451 // to resolve macros in it. This has nothing to do with
452 // labels, but by putting it here we avoid implementing
453 // a whole bunch of traversal routines just for this call.
454 parit.text()->setMacrocontextPosition(parit);
456 depth_type maxdepth = 0;
457 pit_type const lastpit = parit.lastpit();
458 for ( ; parit.pit() <= lastpit ; ++parit.pit()) {
459 // reduce depth if necessary
460 parit->params().depth(min(parit->params().depth(), maxdepth));
461 maxdepth = parit->getMaxDepthAfter();
463 // set the counter for this paragraph
464 setLabel(buf, parit);
467 InsetList::const_iterator iit = parit->insetList().begin();
468 InsetList::const_iterator end = parit->insetList().end();
469 for (; iit != end; ++iit) {
470 parit.pos() = iit->pos;
471 iit->inset->updateLabels(parit);
477 // FIXME: buf should should be const because updateLabels() modifies
478 // the contents of the paragraphs.
479 void updateLabels(Buffer const & buf, bool childonly)
481 Buffer const * const master = buf.masterBuffer();
482 // Use the master text class also for child documents
483 DocumentClass const & textclass = master->params().documentClass();
486 // If this is a child document start with the master
487 if (master != &buf) {
488 updateLabels(*master);
492 // start over the counters
493 textclass.counters().reset();
494 buf.clearReferenceCache();
497 Buffer & cbuf = const_cast<Buffer &>(buf);
499 if (buf.text().empty()) {
500 // FIXME: we don't call continue with updateLabels()
501 // here because it crashes on newly created documents.
502 // But the TocBackend needs to be initialised
503 // nonetheless so we update the tocBackend manually.
504 cbuf.tocBackend().update();
509 ParIterator parit = par_iterator_begin(buf.inset());
510 updateLabels(buf, parit);
512 cbuf.tocBackend().update();
514 cbuf.structureChanged();