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