]> git.lyx.org Git - features.git/blob - src/buffer_funcs.cpp
Split LyXFunc::menuNew() into LyXView::newDocument() and buffer_funcs::newUnnamedFile().
[features.git] / src / buffer_funcs.cpp
1 /**
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.
5  *
6  * \author Lars Gullik Bjønnes
7  * \author Alfredo Braunstein
8  *
9  * Full author contact details are available in file CREDITS.
10  *
11  */
12
13 #include <config.h>
14
15 #include "buffer_funcs.h"
16 #include "Buffer.h"
17 #include "BufferList.h"
18 #include "BufferParams.h"
19 #include "DocIterator.h"
20 #include "Counters.h"
21 #include "ErrorList.h"
22 #include "Floating.h"
23 #include "FloatList.h"
24 #include "InsetList.h"
25 #include "InsetIterator.h"
26 #include "Language.h"
27 #include "LaTeX.h"
28 #include "Layout.h"
29 #include "LayoutPtr.h"
30 #include "LyX.h"
31 #include "TextClass.h"
32 #include "TextClassList.h"
33 #include "Paragraph.h"
34 #include "paragraph_funcs.h"
35 #include "ParagraphList.h"
36 #include "ParagraphParameters.h"
37 #include "ParIterator.h"
38 #include "TexRow.h"
39 #include "Text.h"
40 #include "TocBackend.h"
41
42 #include "frontends/alert.h"
43
44 #include "insets/InsetBibitem.h"
45 #include "insets/InsetInclude.h"
46
47 #include "support/convert.h"
48 #include "support/debug.h"
49 #include "support/filetools.h"
50 #include "support/gettext.h"
51 #include "support/lstrings.h"
52 #include "support/lyxlib.h"
53
54
55 namespace lyx {
56
57 using namespace std;
58
59 using support::addName;
60 using support::bformat;
61 using support::FileName;
62 using support::libFileSearch;
63 using support::makeAbsPath;
64 using support::makeDisplayPath;
65 using support::onlyFilename;
66 using support::onlyPath;
67
68 namespace Alert = frontend::Alert;
69
70
71 Buffer * checkAndLoadLyXFile(FileName const & filename)
72 {
73         // File already open?
74         Buffer * checkBuffer = theBufferList().getBuffer(filename.absFilename());
75         if (checkBuffer) {
76                 if (checkBuffer->isClean())
77                         return checkBuffer;
78                 docstring const file = makeDisplayPath(filename.absFilename(), 20);
79                 docstring text = bformat(_(
80                                 "The document %1$s is already loaded and has unsaved changes.\n"
81                                 "Do you want to abandon your changes and reload the version on disk?"), file);
82                 if (Alert::prompt(_("Reload saved document?"),
83                                 text, 0, 1,  _("&Reload"), _("&Keep Changes")))
84                         return checkBuffer;
85
86                 // FIXME: should be LFUN_REVERT
87                 theBufferList().release(checkBuffer);
88                 // Load it again.
89                 return checkAndLoadLyXFile(filename);
90         }
91
92         if (filename.isReadableFile()) {
93                 Buffer * b = theBufferList().newBuffer(filename.absFilename());
94                 if (!b->loadLyXFile(filename)) {
95                         theBufferList().release(b);
96                         return 0;
97                 }
98                 return b;
99         }
100
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);
107
108         return 0;
109 }
110
111
112 // FIXME newFile() should probably be a member method of Application...
113 Buffer * newFile(string const & filename, string const & templatename,
114                  bool const isNamed)
115 {
116         // get a free buffer
117         Buffer * b = theBufferList().newBuffer(filename);
118         BOOST_ASSERT(b);
119
120         FileName tname;
121         // use defaults.lyx as a default template if it exists.
122         if (templatename.empty())
123                 tname = libFileSearch("templates", "defaults.lyx");
124         else
125                 tname = makeAbsPath(templatename);
126
127         if (!tname.empty()) {
128                 if (!b->readFile(tname)) {
129                         docstring const file = makeDisplayPath(tname.absFilename(), 50);
130                         docstring const text  = bformat(
131                                 _("The specified document template\n%1$s\ncould not be read."),
132                                 file);
133                         Alert::error(_("Could not read template"), text);
134                         theBufferList().release(b);
135                         return 0;
136                 }
137         }
138
139         if (!isNamed) {
140                 b->setUnnamed();
141                 b->setFileName(filename);
142         }
143
144         b->setReadonly(false);
145         b->setFullyLoaded(true);
146
147         return b;
148 }
149
150
151 Buffer * newUnnamedFile(string const & templatename, FileName const & path)
152 {
153         static int newfile_number;
154
155         string document_path = path.absFilename();
156         string filename = addName(document_path,
157                 "newfile" + convert<string>(++newfile_number) + ".lyx");
158         while (theBufferList().exists(filename)
159                 || FileName(filename).isReadableFile()) {
160                 ++newfile_number;
161                 filename = addName(document_path,
162                         "newfile" +     convert<string>(newfile_number) + ".lyx");
163         }
164         return newFile(filename, templatename, false);
165 }
166
167
168 int countWords(DocIterator const & from, DocIterator const & to)
169 {
170         int count = 0;
171         bool inword = false;
172         for (DocIterator dit = from ; dit != to ; dit.forwardPos()) {
173                 // Copied and adapted from isLetter() in ControlSpellChecker
174                 if (dit.inTexted()
175                     && dit.pos() != dit.lastpos()
176                     && dit.paragraph().isLetter(dit.pos())
177                     && !dit.paragraph().isDeleted(dit.pos())) {
178                         if (!inword) {
179                                 ++count;
180                                 inword = true;
181                         }
182                 } else if (inword)
183                         inword = false;
184         }
185
186         return count;
187 }
188
189
190 namespace {
191
192 depth_type getDepth(DocIterator const & it)
193 {
194         depth_type depth = 0;
195         for (size_t i = 0 ; i < it.depth() ; ++i)
196                 if (!it[i].inset().inMathed())
197                         depth += it[i].paragraph().getDepth() + 1;
198         // remove 1 since the outer inset does not count
199         return depth - 1;
200 }
201
202 depth_type getItemDepth(ParIterator const & it)
203 {
204         Paragraph const & par = *it;
205         LabelType const labeltype = par.layout()->labeltype;
206
207         if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
208                 return 0;
209
210         // this will hold the lowest depth encountered up to now.
211         depth_type min_depth = getDepth(it);
212         ParIterator prev_it = it;
213         while (true) {
214                 if (prev_it.pit())
215                         --prev_it.top().pit();
216                 else {
217                         // start of nested inset: go to outer par
218                         prev_it.pop_back();
219                         if (prev_it.empty()) {
220                                 // start of document: nothing to do
221                                 return 0;
222                         }
223                 }
224
225                 // We search for the first paragraph with same label
226                 // that is not more deeply nested.
227                 Paragraph & prev_par = *prev_it;
228                 depth_type const prev_depth = getDepth(prev_it);
229                 if (labeltype == prev_par.layout()->labeltype) {
230                         if (prev_depth < min_depth)
231                                 return prev_par.itemdepth + 1;
232                         if (prev_depth == min_depth)
233                                 return prev_par.itemdepth;
234                 }
235                 min_depth = std::min(min_depth, prev_depth);
236                 // small optimization: if we are at depth 0, we won't
237                 // find anything else
238                 if (prev_depth == 0)
239                         return 0;
240         }
241 }
242
243
244 bool needEnumCounterReset(ParIterator const & it)
245 {
246         Paragraph const & par = *it;
247         BOOST_ASSERT(par.layout()->labeltype == LABEL_ENUMERATE);
248         depth_type const cur_depth = par.getDepth();
249         ParIterator prev_it = it;
250         while (prev_it.pit()) {
251                 --prev_it.top().pit();
252                 Paragraph const & prev_par = *prev_it;
253                 if (prev_par.getDepth() <= cur_depth)
254                         return  prev_par.layout()->labeltype != LABEL_ENUMERATE;
255         }
256         // start of nested inset: reset
257         return true;
258 }
259
260
261 // set the label of a paragraph. This includes the counters.
262 void setLabel(Buffer const & buf, ParIterator & it)
263 {
264         TextClass const & textclass = buf.params().getTextClass();
265         Paragraph & par = it.paragraph();
266         LayoutPtr const & layout = par.layout();
267         Counters & counters = textclass.counters();
268
269         if (par.params().startOfAppendix()) {
270                 // FIXME: only the counter corresponding to toplevel
271                 // sectionning should be reset
272                 counters.reset();
273                 counters.appendix(true);
274         }
275         par.params().appendix(counters.appendix());
276
277         // Compute the item depth of the paragraph
278         par.itemdepth = getItemDepth(it);
279
280         if (layout->margintype == MARGIN_MANUAL) {
281                 if (par.params().labelWidthString().empty())
282                         par.params().labelWidthString(par.translateIfPossible(layout->labelstring(), buf.params()));
283         } else {
284                 par.params().labelWidthString(docstring());
285         }
286
287         switch(layout->labeltype) {
288         case LABEL_COUNTER:
289                 if (layout->toclevel <= buf.params().secnumdepth
290                     && (layout->latextype != LATEX_ENVIRONMENT
291                         || isFirstInSequence(it.pit(), it.plist()))) {
292                         counters.step(layout->counter);
293                         par.params().labelString(
294                                 par.expandLabel(layout, buf.params()));
295                 } else
296                         par.params().labelString(docstring());
297                 break;
298
299         case LABEL_ITEMIZE: {
300                 // At some point of time we should do something more
301                 // clever here, like:
302                 //   par.params().labelString(
303                 //    buf.params().user_defined_bullet(par.itemdepth).getText());
304                 // for now, use a simple hardcoded label
305                 docstring itemlabel;
306                 switch (par.itemdepth) {
307                 case 0:
308                         itemlabel = char_type(0x2022);
309                         break;
310                 case 1:
311                         itemlabel = char_type(0x2013);
312                         break;
313                 case 2:
314                         itemlabel = char_type(0x2217);
315                         break;
316                 case 3:
317                         itemlabel = char_type(0x2219); // or 0x00b7
318                         break;
319                 }
320                 par.params().labelString(itemlabel);
321                 break;
322         }
323
324         case LABEL_ENUMERATE: {
325                 // FIXME: Yes I know this is a really, really! bad solution
326                 // (Lgb)
327                 docstring enumcounter = from_ascii("enum");
328
329                 switch (par.itemdepth) {
330                 case 2:
331                         enumcounter += 'i';
332                 case 1:
333                         enumcounter += 'i';
334                 case 0:
335                         enumcounter += 'i';
336                         break;
337                 case 3:
338                         enumcounter += "iv";
339                         break;
340                 default:
341                         // not a valid enumdepth...
342                         break;
343                 }
344
345                 // Maybe we have to reset the enumeration counter.
346                 if (needEnumCounterReset(it))
347                         counters.reset(enumcounter);
348
349                 counters.step(enumcounter);
350
351                 string format;
352
353                 switch (par.itemdepth) {
354                 case 0:
355                         format = N_("\\arabic{enumi}.");
356                         break;
357                 case 1:
358                         format = N_("(\\alph{enumii})");
359                         break;
360                 case 2:
361                         format = N_("\\roman{enumiii}.");
362                         break;
363                 case 3:
364                         format = N_("\\Alph{enumiv}.");
365                         break;
366                 default:
367                         // not a valid enumdepth...
368                         break;
369                 }
370
371                 par.params().labelString(counters.counterLabel(
372                         par.translateIfPossible(from_ascii(format), buf.params())));
373
374                 break;
375         }
376
377         case LABEL_SENSITIVE: {
378                 string const & type = counters.current_float();
379                 docstring full_label;
380                 if (type.empty())
381                         full_label = buf.B_("Senseless!!! ");
382                 else {
383                         docstring name = buf.B_(textclass.floats().getType(type).name());
384                         if (counters.hasCounter(from_utf8(type))) {
385                                 counters.step(from_utf8(type));
386                                 full_label = bformat(from_ascii("%1$s %2$s:"), 
387                                                      name, 
388                                                      counters.theCounter(from_utf8(type)));
389                         } else
390                                 full_label = bformat(from_ascii("%1$s #:"), name);      
391                 }
392                 par.params().labelString(full_label);   
393                 break;
394         }
395
396         case LABEL_NO_LABEL:
397                 par.params().labelString(docstring());
398                 break;
399
400         case LABEL_MANUAL:
401         case LABEL_TOP_ENVIRONMENT:
402         case LABEL_CENTERED_TOP_ENVIRONMENT:
403         case LABEL_STATIC:      
404         case LABEL_BIBLIO:
405                 par.params().labelString(
406                         par.translateIfPossible(layout->labelstring(), 
407                                                 buf.params()));
408                 break;
409         }
410 }
411
412 } // anon namespace
413
414 void updateLabels(Buffer const & buf, ParIterator & parit)
415 {
416         BOOST_ASSERT(parit.pit() == 0);
417
418         depth_type maxdepth = 0;
419         pit_type const lastpit = parit.lastpit();
420         for ( ; parit.pit() <= lastpit ; ++parit.pit()) {
421                 // reduce depth if necessary
422                 parit->params().depth(min(parit->params().depth(), maxdepth));
423                 maxdepth = parit->getMaxDepthAfter();
424
425                 // set the counter for this paragraph
426                 setLabel(buf, parit);
427
428                 // Now the insets
429                 InsetList::const_iterator iit = parit->insetList().begin();
430                 InsetList::const_iterator end = parit->insetList().end();
431                 for (; iit != end; ++iit) {
432                         parit.pos() = iit->pos;
433                         iit->inset->updateLabels(buf, parit);
434                 }
435         }
436         
437 }
438
439
440 // FIXME: buf should should be const because updateLabels() modifies
441 // the contents of the paragraphs.
442 void updateLabels(Buffer const & buf, bool childonly)
443 {
444         Buffer const * const master = buf.masterBuffer();
445         // Use the master text class also for child documents
446         TextClass const & textclass = master->params().getTextClass();
447
448         if (!childonly) {
449                 // If this is a child document start with the master
450                 if (master != &buf) {
451                         updateLabels(*master);
452                         return;
453                 }
454
455                 // start over the counters
456                 textclass.counters().reset();
457         }
458
459         Buffer & cbuf = const_cast<Buffer &>(buf);
460
461         if (buf.text().empty()) {
462                 // FIXME: we don't call continue with updateLabels()
463                 // here because it crashes on newly created documents.
464                 // But the TocBackend needs to be initialised
465                 // nonetheless so we update the tocBackend manually.
466                 cbuf.tocBackend().update();
467                 return;
468         }
469
470         // do the real work
471         ParIterator parit = par_iterator_begin(buf.inset());
472         updateLabels(buf, parit);
473
474         cbuf.tocBackend().update();
475         if (!childonly)
476                 cbuf.structureChanged();
477 }
478
479
480 void checkBufferStructure(Buffer & buffer, ParIterator const & par_it)
481 {
482         if (par_it->layout()->toclevel != Layout::NOT_IN_TOC) {
483                 Buffer const * master = buffer.masterBuffer();
484                 master->tocBackend().updateItem(par_it);
485                 master->structureChanged();
486         }
487 }
488
489
490 } // namespace lyx