]> git.lyx.org Git - lyx.git/blob - src/buffer.C
45f9484dbb1ede7c322467a07882c607fe20c0db
[lyx.git] / src / buffer.C
1 /**
2  * \file buffer.C
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  *
8  * Full author contact details are available in file CREDITS.
9  */
10
11 #include <config.h>
12
13 #include "buffer.h"
14
15 #include "author.h"
16 #include "buffer_funcs.h"
17 #include "bufferlist.h"
18 #include "bufferparams.h"
19 #include "Bullet.h"
20 #include "Chktex.h"
21 #include "debug.h"
22 #include "errorlist.h"
23 #include "exporter.h"
24 #include "format.h"
25 #include "gettext.h"
26 #include "iterators.h"
27 #include "language.h"
28 #include "LaTeX.h"
29 #include "LaTeXFeatures.h"
30 #include "LyXAction.h"
31 #include "lyxlex.h"
32 #include "lyxrc.h"
33 #include "lyxvc.h"
34 #include "messages.h"
35 #include "paragraph_funcs.h"
36 #include "ParagraphParameters.h"
37 #include "sgml.h"
38 #include "texrow.h"
39 #include "undo.h"
40 #include "version.h"
41
42 #include "insets/insetbibitem.h"
43 #include "insets/insetbibtex.h"
44 #include "insets/insetinclude.h"
45 #include "insets/insettext.h"
46
47 #include "frontends/Alert.h"
48
49 #include "graphics/Previews.h"
50
51 #include "support/FileInfo.h"
52 #include "support/filetools.h"
53 #include "support/gzstream.h"
54 #include "support/LAssert.h"
55 #include "support/lyxlib.h"
56 #include "support/os.h"
57 #include "support/path.h"
58 #include "support/textutils.h"
59 #include "support/tostr.h"
60
61 #include <boost/bind.hpp>
62 #include <boost/tuple/tuple.hpp>
63
64 #include "support/std_sstream.h"
65
66 #include <iomanip>
67 #include <stack>
68
69 #include <utime.h>
70
71 #ifdef HAVE_LOCALE
72 #endif
73
74 using namespace lyx::support;
75
76 using std::endl;
77 using std::for_each;
78 using std::make_pair;
79
80 using std::ifstream;
81 using std::list;
82 using std::ios;
83 using std::ostream;
84 using std::ostringstream;
85 using std::ofstream;
86 using std::pair;
87 using std::stack;
88 using std::vector;
89
90 using lyx::pos_type;
91
92
93 // all these externs should eventually be removed.
94 extern BufferList bufferlist;
95
96 namespace {
97
98 const int LYX_FORMAT = 225;
99
100 bool openFileWrite(ofstream & ofs, string const & fname)
101 {
102         ofs.open(fname.c_str());
103         if (!ofs) {
104                 string const file = MakeDisplayPath(fname, 50);
105                 string text = bformat(_("Could not open the specified "
106                                         "document\n%1$s."), file);
107                 Alert::error(_("Could not open file"), text);
108                 return false;
109         }
110         return true;
111 }
112
113 } // namespace anon
114
115
116 typedef std::map<string, bool> DepClean;
117
118 struct Buffer::Impl 
119 {
120         Impl(Buffer & parent, string const & file, bool readonly);
121
122         limited_stack<Undo> undostack;
123         limited_stack<Undo> redostack;
124         BufferParams params;
125         ParagraphList paragraphs;
126         LyXVC lyxvc;
127         string temppath;
128         bool nicefile;
129         TexRow texrow;
130
131         /// need to regenerate .tex ?
132         DepClean dep_clean;
133
134         /// is save needed
135         mutable bool lyx_clean;
136
137         /// is autosave needed
138         mutable bool bak_clean;
139
140         /// is this a unnamed file (New...)
141         bool unnamed;
142
143         /// buffer is r/o
144         bool read_only;
145
146         /// name of the file the buffer is associated with.
147         string filename;
148
149         /// The path to the document file.
150         string filepath;
151
152         boost::scoped_ptr<Messages> messages;
153 };
154
155
156 Buffer::Impl::Impl(Buffer & parent, string const & file, bool readonly_)
157         : nicefile(true),
158           lyx_clean(true), bak_clean(true), unnamed(false), read_only(readonly_),
159           filename(file), filepath(OnlyPath(file))
160 {
161         lyxvc.buffer(&parent);
162         if (readonly_ || lyxrc.use_tempdir)
163                 temppath = CreateBufferTmpDir();
164 }
165
166
167 Buffer::Buffer(string const & file, bool ronly)
168         : pimpl_(new Impl(*this, file, ronly))
169 {
170         lyxerr[Debug::INFO] << "Buffer::Buffer()" << endl;
171 }
172
173
174 Buffer::~Buffer()
175 {
176         lyxerr[Debug::INFO] << "Buffer::~Buffer()" << endl;
177         // here the buffer should take care that it is
178         // saved properly, before it goes into the void.
179
180         closing();
181
182         if (!temppath().empty() && destroyDir(temppath()) != 0) {
183                 Alert::warning(_("Could not remove temporary directory"),
184                         bformat(_("Could not remove the temporary directory %1$s"), temppath()));
185         }
186
187         paragraphs().clear();
188
189         // Remove any previewed LaTeX snippets associated with this buffer.
190         lyx::graphics::Previews::get().removeLoader(*this);
191 }
192
193
194 limited_stack<Undo> & Buffer::undostack()
195 {
196         return pimpl_->undostack;
197 }
198
199
200 limited_stack<Undo> const & Buffer::undostack() const
201 {
202         return pimpl_->undostack;
203 }
204
205
206 limited_stack<Undo> & Buffer::redostack()
207 {
208         return pimpl_->redostack;
209 }
210
211
212 limited_stack<Undo> const & Buffer::redostack() const
213 {
214         return pimpl_->redostack;
215 }
216
217
218 BufferParams & Buffer::params()
219 {
220         return pimpl_->params;
221 }
222
223
224 BufferParams const & Buffer::params() const
225 {
226         return pimpl_->params;
227 }
228
229
230 ParagraphList & Buffer::paragraphs()
231 {
232         return pimpl_->paragraphs;
233 }
234
235
236 ParagraphList const & Buffer::paragraphs() const
237 {
238         return pimpl_->paragraphs;
239 }
240
241
242 LyXVC & Buffer::lyxvc()
243 {
244         return pimpl_->lyxvc;
245 }
246
247
248 LyXVC const & Buffer::lyxvc() const
249 {
250         return pimpl_->lyxvc;
251 }
252
253
254 string const & Buffer::temppath() const
255 {
256         return pimpl_->temppath;
257 }
258
259
260 bool & Buffer::niceFile()
261 {
262         return pimpl_->nicefile;
263 }
264
265
266 bool Buffer::niceFile() const
267 {
268         return pimpl_->nicefile;
269 }
270
271
272 TexRow & Buffer::texrow()
273 {
274         return pimpl_->texrow;
275 }
276
277
278 TexRow const & Buffer::texrow() const
279 {
280         return pimpl_->texrow;
281 }
282
283
284 string const Buffer::getLatexName(bool no_path) const
285 {
286         string const name = ChangeExtension(MakeLatexName(fileName()), ".tex");
287         return no_path ? OnlyFilename(name) : name;
288 }
289
290
291 pair<Buffer::LogType, string> const Buffer::getLogName() const
292 {
293         string const filename = getLatexName(false);
294
295         if (filename.empty())
296                 return make_pair(Buffer::latexlog, string());
297
298         string path = OnlyPath(filename);
299
300         if (lyxrc.use_tempdir || !IsDirWriteable(path))
301                 path = temppath();
302
303         string const fname = AddName(path,
304                                      OnlyFilename(ChangeExtension(filename,
305                                                                   ".log")));
306         string const bname =
307                 AddName(path, OnlyFilename(
308                         ChangeExtension(filename,
309                                         formats.extension("literate") + ".out")));
310
311         // If no Latex log or Build log is newer, show Build log
312
313         FileInfo const f_fi(fname);
314         FileInfo const b_fi(bname);
315
316         if (b_fi.exist() &&
317             (!f_fi.exist() || f_fi.getModificationTime() < b_fi.getModificationTime())) {
318                 lyxerr[Debug::FILES] << "Log name calculated as: " << bname << endl;
319                 return make_pair(Buffer::buildlog, bname);
320         }
321         lyxerr[Debug::FILES] << "Log name calculated as: " << fname << endl;
322         return make_pair(Buffer::latexlog, fname);
323 }
324
325
326 void Buffer::setReadonly(bool flag)
327 {
328         if (pimpl_->read_only != flag) {
329                 pimpl_->read_only = flag;
330                 readonly(flag);
331         }
332 }
333
334
335 void Buffer::setFileName(string const & newfile)
336 {
337         pimpl_->filename = MakeAbsPath(newfile);
338         pimpl_->filepath = OnlyPath(pimpl_->filename);
339         setReadonly(IsFileWriteable(pimpl_->filename) == 0);
340         updateTitles();
341 }
342
343
344 // We'll remove this later. (Lgb)
345 namespace {
346
347 void unknownClass(string const & unknown)
348 {
349         Alert::warning(_("Unknown document class"),
350                 bformat(_("Using the default document class, because the "
351                         "class %1$s is unknown."), unknown));
352 }
353
354 } // anon
355
356 int Buffer::readHeader(LyXLex & lex)
357 {
358         int unknown_tokens = 0;
359
360         while (lex.isOK()) {
361                 lex.nextToken();
362                 string const token = lex.getString();
363
364                 if (token.empty())
365                         continue;
366
367                 if (token == "\\end_header")
368                         break;
369
370                 lyxerr[Debug::PARSER] << "Handling header token: `"
371                                       << token << '\'' << endl;
372
373
374                 string unknown = params().readToken(lex, token);
375                 if (!unknown.empty()) {
376                         if (unknown[0] != '\\') {
377                                 unknownClass(unknown);
378                         } else {
379                                 ++unknown_tokens;
380                                 string const s = bformat(_("Unknown token: "
381                                                            "%1$s %2$s\n"),
382                                                          token,
383                                                          lex.getString());
384                                 error(ErrorItem(_("Header error"), s,
385                                                 -1, 0, 0));
386                         }
387                 }
388         }
389         return unknown_tokens;
390 }
391
392
393 // candidate for move to BufferView
394 // (at least some parts in the beginning of the func)
395 //
396 // Uwe C. Schroeder
397 // changed to be public and have one parameter
398 // if par = 0 normal behavior
399 // else insert behavior
400 // Returns false if "\end_document" is not read (Asger)
401 bool Buffer::readBody(LyXLex & lex, ParagraphList::iterator pit)
402 {
403         Paragraph::depth_type depth = 0;
404         bool the_end_read = false;
405
406         if (paragraphs().empty()) {
407                 readHeader(lex);
408                 if (!params().getLyXTextClass().load()) {
409                         string theclass = params().getLyXTextClass().name();
410                         Alert::error(_("Can't load document class"), bformat(
411                                         "Using the default document class, because the "
412                                         " class %1$s could not be loaded.", theclass));
413                         params().textclass = 0;
414                 }
415         } else {
416                 // We don't want to adopt the parameters from the
417                 // document we insert, so read them into a temporary buffer
418                 // and then discard it
419
420                 Buffer tmpbuf("", false);
421                 tmpbuf.readHeader(lex);
422         }
423
424         while (lex.isOK()) {
425                 lex.nextToken();
426                 string const token = lex.getString();
427
428                 if (token.empty())
429                         continue;
430
431                 lyxerr[Debug::PARSER] << "Handling token: `"
432                                       << token << '\'' << endl;
433
434                 if (token == "\\end_document") {
435                         the_end_read = true;
436                         continue;
437                 }
438
439                 readParagraph(lex, token, paragraphs(), pit, depth);
440         }
441
442         return the_end_read;
443 }
444
445
446 int Buffer::readParagraph(LyXLex & lex, string const & token,
447                           ParagraphList & pars, ParagraphList::iterator & pit,
448                           Paragraph::depth_type & depth)
449 {
450         static Change current_change;
451         int unknown = 0;
452
453         if (token == "\\begin_layout") {
454                 lex.pushToken(token);
455
456                 Paragraph par;
457                 par.params().depth(depth);
458                 if (params().tracking_changes)
459                         par.trackChanges();
460                 LyXFont f(LyXFont::ALL_INHERIT, params().language);
461                 par.setFont(0, f);
462
463                 // insert after
464                 if (pit != pars.end())
465                         ++pit;
466
467                 pit = pars.insert(pit, par);
468
469                 // FIXME: goddamn InsetTabular makes us pass a Buffer
470                 // not BufferParams
471                 ::readParagraph(*this, *pit, lex);
472
473         } else if (token == "\\begin_deeper") {
474                 ++depth;
475         } else if (token == "\\end_deeper") {
476                 if (!depth) {
477                         lex.printError("\\end_deeper: " "depth is already null");
478                 } else {
479                         --depth;
480                 }
481         } else {
482                 ++unknown;
483         }
484         return unknown;
485 }
486
487
488 // needed to insert the selection
489 void Buffer::insertStringAsLines(ParagraphList::iterator & par, pos_type & pos,
490                                  LyXFont const & fn,string const & str)
491 {
492         LyXLayout_ptr const & layout = par->layout();
493
494         LyXFont font = fn;
495
496         par->checkInsertChar(font);
497         // insert the string, don't insert doublespace
498         bool space_inserted = true;
499         bool autobreakrows = !par->inInset() ||
500                 static_cast<InsetText *>(par->inInset())->getAutoBreakRows();
501         for(string::const_iterator cit = str.begin();
502             cit != str.end(); ++cit) {
503                 if (*cit == '\n') {
504                         if (autobreakrows && (!par->empty() || par->allowEmpty())) {
505                                 breakParagraph(params(), paragraphs(), par, pos,
506                                                layout->isEnvironment());
507                                 ++par;
508                                 pos = 0;
509                                 space_inserted = true;
510                         } else {
511                                 continue;
512                         }
513                         // do not insert consecutive spaces if !free_spacing
514                 } else if ((*cit == ' ' || *cit == '\t') &&
515                            space_inserted && !par->isFreeSpacing()) {
516                         continue;
517                 } else if (*cit == '\t') {
518                         if (!par->isFreeSpacing()) {
519                                 // tabs are like spaces here
520                                 par->insertChar(pos, ' ', font);
521                                 ++pos;
522                                 space_inserted = true;
523                         } else {
524                                 const pos_type nb = 8 - pos % 8;
525                                 for (pos_type a = 0; a < nb ; ++a) {
526                                         par->insertChar(pos, ' ', font);
527                                         ++pos;
528                                 }
529                                 space_inserted = true;
530                         }
531                 } else if (!IsPrintable(*cit)) {
532                         // Ignore unprintables
533                         continue;
534                 } else {
535                         // just insert the character
536                         par->insertChar(pos, *cit, font);
537                         ++pos;
538                         space_inserted = (*cit == ' ');
539                 }
540
541         }
542 }
543
544
545 bool Buffer::readFile(string const & filename)
546 {
547         // Check if the file is compressed.
548         string const format = getExtFromContents(filename);
549         if (format == "gzip" || format == "zip" || format == "compress") {
550                 params().compressed = true;
551         }
552
553         bool ret = readFile(filename, paragraphs().begin());
554
555         // After we have read a file, we must ensure that the buffer
556         // language is set and used in the gui.
557         // If you know of a better place to put this, please tell me. (Lgb)
558         updateDocLang(params().language);
559
560         return ret;
561 }
562
563
564 bool Buffer::readFile(string const & filename, ParagraphList::iterator pit)
565 {
566         LyXLex lex(0, 0);
567         lex.setFile(filename);
568
569         return readFile(lex, filename, pit);
570 }
571
572
573 bool Buffer::readFile(LyXLex & lex, string const & filename,
574                       ParagraphList::iterator pit)
575 {
576         Assert(!filename.empty());
577
578         if (!lex.isOK()) {
579                 Alert::error(_("Document could not be read"),
580                              bformat(_("%1$s could not be read."), filename));
581                 return false;
582         }
583
584         lex.next();
585         string const token(lex.getString());
586
587         if (!lex.isOK()) {
588                 Alert::error(_("Document could not be read"),
589                              bformat(_("%1$s could not be read."), filename));
590                 return false;
591         }
592
593         // the first token _must_ be...
594         if (token != "\\lyxformat") {
595                 lyxerr << "Token: " << token << endl;
596
597                 Alert::error(_("Document format failure"),
598                              bformat(_("%1$s is not a LyX document."),
599                                        filename));
600                 return false;
601         }
602
603         lex.eatLine();
604         string tmp_format = lex.getString();
605         //lyxerr << "LyX Format: `" << tmp_format << '\'' << endl;
606         // if present remove ".," from string.
607         string::size_type dot = tmp_format.find_first_of(".,");
608         //lyxerr << "           dot found at " << dot << endl;
609         if (dot != string::npos)
610                         tmp_format.erase(dot, 1);
611         int file_format = strToInt(tmp_format);
612         //lyxerr << "format: " << file_format << endl;
613
614         if (file_format > LYX_FORMAT) {
615                 Alert::warning(_("Document format failure"),
616                                bformat(_("%1$s was created with a newer"
617                                          " version of LyX. This is likely to"
618                                          " cause problems."),
619                                          filename));
620         } else if (file_format < LYX_FORMAT) {
621                 string const tmpfile = tempName();
622                 string command = LibFileSearch("lyx2lyx", "lyx2lyx");
623                 if (command.empty()) {
624                         Alert::error(_("Conversion script not found"),
625                                      bformat(_("%1$s is from an earlier"
626                                                " version of LyX, but the"
627                                                " conversion script lyx2lyx"
628                                                " could not be found."),
629                                                filename));
630                         return false;
631                 }
632                 command += " -t"
633                         + tostr(LYX_FORMAT)
634                         + " -o " + tmpfile + ' '
635                         + QuoteName(filename);
636                 lyxerr[Debug::INFO] << "Running '"
637                                     << command << '\''
638                                     << endl;
639                 cmd_ret const ret = RunCommand(command);
640                 if (ret.first != 0) {
641                         Alert::error(_("Conversion script failed"),
642                                      bformat(_("%1$s is from an earlier version"
643                                               " of LyX, but the lyx2lyx script"
644                                               " failed to convert it."),
645                                               filename));
646                         return false;
647                 } else {
648                         bool ret = readFile(tmpfile, pit);
649                         // Do stuff with tmpfile name and buffer name here.
650                         return ret;
651                 }
652
653         }
654
655         bool the_end = readBody(lex, pit);
656         params().setPaperStuff();
657
658         if (!the_end) {
659                 Alert::error(_("Document format failure"),
660                              bformat(_("%1$s ended unexpectedly, which means"
661                                        " that it is probably corrupted."),
662                                        filename));
663         }
664         return true;
665 }
666
667
668 // Should probably be moved to somewhere else: BufferView? LyXView?
669 bool Buffer::save() const
670 {
671         // We don't need autosaves in the immediate future. (Asger)
672         resetAutosaveTimers();
673
674         // make a backup
675         string s;
676         if (lyxrc.make_backup) {
677                 s = fileName() + '~';
678                 if (!lyxrc.backupdir_path.empty())
679                         s = AddName(lyxrc.backupdir_path,
680                                     subst(os::slashify_path(s),'/','!'));
681
682                 // Rename is the wrong way of making a backup,
683                 // this is the correct way.
684                 /* truss cp fil fil2:
685                    lstat("LyXVC3.lyx", 0xEFFFF898)                 Err#2 ENOENT
686                    stat("LyXVC.lyx", 0xEFFFF688)                   = 0
687                    open("LyXVC.lyx", O_RDONLY)                     = 3
688                    open("LyXVC3.lyx", O_WRONLY|O_CREAT|O_TRUNC, 0600) = 4
689                    fstat(4, 0xEFFFF508)                            = 0
690                    fstat(3, 0xEFFFF508)                            = 0
691                    read(3, " # T h i s   f i l e   w".., 8192)     = 5579
692                    write(4, " # T h i s   f i l e   w".., 5579)    = 5579
693                    read(3, 0xEFFFD4A0, 8192)                       = 0
694                    close(4)                                        = 0
695                    close(3)                                        = 0
696                    chmod("LyXVC3.lyx", 0100644)                    = 0
697                    lseek(0, 0, SEEK_CUR)                           = 46440
698                    _exit(0)
699                 */
700
701                 // Should probably have some more error checking here.
702                 // Doing it this way, also makes the inodes stay the same.
703                 // This is still not a very good solution, in particular we
704                 // might loose the owner of the backup.
705                 FileInfo finfo(fileName());
706                 if (finfo.exist()) {
707                         mode_t fmode = finfo.getMode();
708                         struct utimbuf times = {
709                                 finfo.getAccessTime(),
710                                 finfo.getModificationTime() };
711
712                         ifstream ifs(fileName().c_str());
713                         ofstream ofs(s.c_str(), ios::out|ios::trunc);
714                         if (ifs && ofs) {
715                                 ofs << ifs.rdbuf();
716                                 ifs.close();
717                                 ofs.close();
718                                 ::chmod(s.c_str(), fmode);
719
720                                 if (::utime(s.c_str(), &times)) {
721                                         lyxerr << "utime error." << endl;
722                                 }
723                         } else {
724                                 lyxerr << "LyX was not able to make "
725                                         "backup copy. Beware." << endl;
726                         }
727                 }
728         }
729
730         if (writeFile(fileName())) {
731                 markClean();
732                 removeAutosaveFile(fileName());
733         } else {
734                 // Saving failed, so backup is not backup
735                 if (lyxrc.make_backup) {
736                         rename(s, fileName());
737                 }
738                 return false;
739         }
740         return true;
741 }
742
743
744 bool Buffer::writeFile(string const & fname) const
745 {
746         if (pimpl_->read_only && (fname == fileName())) {
747                 return false;
748         }
749
750         FileInfo finfo(fname);
751         if (finfo.exist() && !finfo.writable()) {
752                 return false;
753         }
754
755         bool retval;
756
757         if (params().compressed) {
758                 gz::ogzstream ofs(fname.c_str());
759
760                 if (!ofs)
761                         return false;
762
763                 retval = do_writeFile(ofs);
764
765         } else {
766                 ofstream ofs(fname.c_str());
767                 if (!ofs)
768                         return false;
769
770                 retval = do_writeFile(ofs);
771         }
772
773         return retval;
774 }
775
776
777 bool Buffer::do_writeFile(ostream & ofs) const
778 {
779
780 #ifdef HAVE_LOCALE
781         // Use the standard "C" locale for file output.
782         ofs.imbue(std::locale::classic());
783 #endif
784
785         // The top of the file should not be written by params().
786
787         // write out a comment in the top of the file
788         ofs << "#LyX " << lyx_version
789             << " created this file. For more info see http://www.lyx.org/\n"
790             << "\\lyxformat " << LYX_FORMAT << "\n";
791
792         // now write out the buffer paramters.
793         params().writeFile(ofs);
794
795         ofs << "\\end_header\n";
796
797         Paragraph::depth_type depth = 0;
798
799         // this will write out all the paragraphs
800         // using recursive descent.
801         ParagraphList::const_iterator pit = paragraphs().begin();
802         ParagraphList::const_iterator pend = paragraphs().end();
803         for (; pit != pend; ++pit)
804                 pit->write(*this, ofs, params(), depth);
805
806         // Write marker that shows file is complete
807         ofs << "\n\\end_document" << endl;
808
809         // Shouldn't really be needed....
810         //ofs.close();
811
812         // how to check if close went ok?
813         // Following is an attempt... (BE 20001011)
814
815         // good() returns false if any error occured, including some
816         //        formatting error.
817         // bad()  returns true if something bad happened in the buffer,
818         //        which should include file system full errors.
819
820         bool status = true;
821         if (!ofs.good()) {
822                 status = false;
823 #if 0
824                 if (ofs.bad()) {
825                         lyxerr << "Buffer::writeFile: BAD ERROR!" << endl;
826                 } else {
827                         lyxerr << "Buffer::writeFile: NOT SO BAD ERROR!"
828                                << endl;
829                 }
830 #endif
831         }
832
833         return status;
834 }
835
836
837 namespace {
838
839 pair<int, string> const addDepth(int depth, int ldepth)
840 {
841         int d = depth * 2;
842         if (ldepth > depth)
843                 d += (ldepth - depth) * 2;
844         return make_pair(d, string(d, ' '));
845 }
846
847 }
848
849
850 string const Buffer::asciiParagraph(Paragraph const & par,
851                                     unsigned int linelen,
852                                     bool noparbreak) const
853 {
854         ostringstream buffer;
855         int ltype = 0;
856         Paragraph::depth_type ltype_depth = 0;
857         bool ref_printed = false;
858         Paragraph::depth_type depth = par.params().depth();
859
860         // First write the layout
861         string const & tmp = par.layout()->name();
862         if (compare_no_case(tmp, "itemize") == 0) {
863                 ltype = 1;
864                 ltype_depth = depth + 1;
865         } else if (compare_ascii_no_case(tmp, "enumerate") == 0) {
866                 ltype = 2;
867                 ltype_depth = depth + 1;
868         } else if (contains(ascii_lowercase(tmp), "ection")) {
869                 ltype = 3;
870                 ltype_depth = depth + 1;
871         } else if (contains(ascii_lowercase(tmp), "aragraph")) {
872                 ltype = 4;
873                 ltype_depth = depth + 1;
874         } else if (compare_ascii_no_case(tmp, "description") == 0) {
875                 ltype = 5;
876                 ltype_depth = depth + 1;
877         } else if (compare_ascii_no_case(tmp, "abstract") == 0) {
878                 ltype = 6;
879                 ltype_depth = 0;
880         } else if (compare_ascii_no_case(tmp, "bibliography") == 0) {
881                 ltype = 7;
882                 ltype_depth = 0;
883         } else {
884                 ltype = 0;
885                 ltype_depth = 0;
886         }
887
888         /* maybe some vertical spaces */
889
890         /* the labelwidthstring used in lists */
891
892         /* some lines? */
893
894         /* some pagebreaks? */
895
896         /* noindent ? */
897
898         /* what about the alignment */
899
900         // linelen <= 0 is special and means we don't have paragraph breaks
901
902         string::size_type currlinelen = 0;
903
904         if (!noparbreak) {
905                 if (linelen > 0)
906                         buffer << "\n\n";
907
908                 buffer << string(depth * 2, ' ');
909                 currlinelen += depth * 2;
910
911                 //--
912                 // we should probably change to the paragraph language in the
913                 // gettext here (if possible) so that strings are outputted in
914                 // the correct language! (20012712 Jug)
915                 //--
916                 switch (ltype) {
917                 case 0: // Standard
918                 case 4: // (Sub)Paragraph
919                 case 5: // Description
920                         break;
921                 case 6: // Abstract
922                         if (linelen > 0) {
923                                 buffer << _("Abstract") << "\n\n";
924                                 currlinelen = 0;
925                         } else {
926                                 string const abst = _("Abstract: ");
927                                 buffer << abst;
928                                 currlinelen += abst.length();
929                         }
930                         break;
931                 case 7: // Bibliography
932                         if (!ref_printed) {
933                                 if (linelen > 0) {
934                                         buffer << _("References") << "\n\n";
935                                         currlinelen = 0;
936                                 } else {
937                                         string const refs = _("References: ");
938                                         buffer << refs;
939                                         currlinelen += refs.length();
940                                 }
941
942                                 ref_printed = true;
943                         }
944                         break;
945                 default:
946                 {
947                         string const parlab = par.params().labelString();
948                         buffer << parlab << ' ';
949                         currlinelen += parlab.length() + 1;
950                 }
951                 break;
952
953                 }
954         }
955
956         if (!currlinelen) {
957                 pair<int, string> p = addDepth(depth, ltype_depth);
958                 buffer << p.second;
959                 currlinelen += p.first;
960         }
961
962         // this is to change the linebreak to do it by word a bit more
963         // intelligent hopefully! (only in the case where we have a
964         // max linelength!) (Jug)
965
966         string word;
967
968         for (pos_type i = 0; i < par.size(); ++i) {
969                 char c = par.getUChar(params(), i);
970                 switch (c) {
971                 case Paragraph::META_INSET:
972                 {
973                         InsetOld const * inset = par.getInset(i);
974                         if (inset) {
975                                 if (linelen > 0) {
976                                         buffer << word;
977                                         currlinelen += word.length();
978                                         word.erase();
979                                 }
980                                 if (inset->ascii(*this, buffer, linelen)) {
981                                         // to be sure it breaks paragraph
982                                         currlinelen += linelen;
983                                 }
984                         }
985                 }
986                 break;
987
988                 default:
989                         if (c == ' ') {
990                                 if (linelen > 0 &&
991                                     currlinelen + word.length() > linelen - 10) {
992                                         buffer << "\n";
993                                         pair<int, string> p = addDepth(depth, ltype_depth);
994                                         buffer << p.second;
995                                         currlinelen = p.first;
996                                 }
997
998                                 buffer << word << ' ';
999                                 currlinelen += word.length() + 1;
1000                                 word.erase();
1001
1002                         } else {
1003                                 if (c != '\0') {
1004                                         word += c;
1005                                 } else {
1006                                         lyxerr[Debug::INFO] <<
1007                                                 "writeAsciiFile: NULL char in structure." << endl;
1008                                 }
1009                                 if ((linelen > 0) &&
1010                                         (currlinelen + word.length()) > linelen)
1011                                 {
1012                                         buffer << "\n";
1013
1014                                         pair<int, string> p =
1015                                                 addDepth(depth, ltype_depth);
1016                                         buffer << p.second;
1017                                         currlinelen = p.first;
1018                                 }
1019                         }
1020                         break;
1021                 }
1022         }
1023         buffer << word;
1024         return STRCONV(buffer.str());
1025 }
1026
1027
1028 void Buffer::writeFileAscii(string const & fname, int linelen)
1029 {
1030         ofstream ofs;
1031         if (!::openFileWrite(ofs, fname))
1032                 return;
1033         writeFileAscii(ofs, linelen);
1034 }
1035
1036
1037 void Buffer::writeFileAscii(ostream & os, int linelen)
1038 {
1039         ParagraphList::iterator beg = paragraphs().begin();
1040         ParagraphList::iterator end = paragraphs().end();
1041         ParagraphList::iterator it = beg;
1042         for (; it != end; ++it) {
1043                 os << asciiParagraph(*it, linelen, it == beg);
1044         }
1045         os << "\n";
1046 }
1047
1048
1049 void Buffer::makeLaTeXFile(string const & fname,
1050                            string const & original_path,
1051                            LatexRunParams const & runparams,
1052                            bool output_preamble, bool output_body)
1053 {
1054         lyxerr[Debug::LATEX] << "makeLaTeXFile..." << endl;
1055
1056         ofstream ofs;
1057         if (!::openFileWrite(ofs, fname))
1058                 return;
1059
1060         makeLaTeXFile(ofs, original_path,
1061                       runparams, output_preamble, output_body);
1062
1063         ofs.close();
1064         if (ofs.fail()) {
1065                 lyxerr << "File was not closed properly." << endl;
1066         }
1067 }
1068
1069
1070 void Buffer::makeLaTeXFile(ostream & os,
1071                            string const & original_path,
1072                            LatexRunParams const & runparams_in,
1073                            bool output_preamble, bool output_body)
1074 {
1075         LatexRunParams runparams = runparams_in;
1076         niceFile() = runparams.nice; // this will be used by Insetincludes.
1077
1078         // validate the buffer.
1079         lyxerr[Debug::LATEX] << "  Validating buffer..." << endl;
1080         LaTeXFeatures features(params());
1081         validate(features);
1082         lyxerr[Debug::LATEX] << "  Buffer validation done." << endl;
1083
1084         texrow().reset();
1085         // The starting paragraph of the coming rows is the
1086         // first paragraph of the document. (Asger)
1087         texrow().start(paragraphs().begin()->id(), 0);
1088
1089         if (output_preamble && runparams.nice) {
1090                 os << "%% LyX " << lyx_version << " created this file.  "
1091                         "For more info, see http://www.lyx.org/.\n"
1092                         "%% Do not edit unless you really know what "
1093                         "you are doing.\n";
1094                 texrow().newline();
1095                 texrow().newline();
1096         }
1097         lyxerr[Debug::INFO] << "lyx header finished" << endl;
1098         // There are a few differences between nice LaTeX and usual files:
1099         // usual is \batchmode and has a
1100         // special input@path to allow the including of figures
1101         // with either \input or \includegraphics (what figinsets do).
1102         // input@path is set when the actual parameter
1103         // original_path is set. This is done for usual tex-file, but not
1104         // for nice-latex-file. (Matthias 250696)
1105         if (output_preamble) {
1106                 if (!runparams.nice) {
1107                         // code for usual, NOT nice-latex-file
1108                         os << "\\batchmode\n"; // changed
1109                         // from \nonstopmode
1110                         texrow().newline();
1111                 }
1112                 if (!original_path.empty()) {
1113                         string inputpath = os::external_path(original_path);
1114                         subst(inputpath, "~", "\\string~");
1115                         os << "\\makeatletter\n"
1116                             << "\\def\\input@path{{"
1117                             << inputpath << "/}}\n"
1118                             << "\\makeatother\n";
1119                         texrow().newline();
1120                         texrow().newline();
1121                         texrow().newline();
1122                 }
1123
1124                 // Write the preamble
1125                 runparams.use_babel = params().writeLaTeX(os, features, texrow());
1126
1127                 if (!output_body)
1128                         return;
1129
1130                 // make the body.
1131                 os << "\\begin{document}\n";
1132                 texrow().newline();
1133         } // output_preamble
1134         lyxerr[Debug::INFO] << "preamble finished, now the body." << endl;
1135
1136         if (!lyxrc.language_auto_begin) {
1137                 os << subst(lyxrc.language_command_begin, "$$lang",
1138                              params().language->babel())
1139                     << endl;
1140                 texrow().newline();
1141         }
1142
1143         latexParagraphs(*this, paragraphs(), os, texrow(), runparams);
1144
1145         // add this just in case after all the paragraphs
1146         os << endl;
1147         texrow().newline();
1148
1149         if (!lyxrc.language_auto_end) {
1150                 os << subst(lyxrc.language_command_end, "$$lang",
1151                              params().language->babel())
1152                     << endl;
1153                 texrow().newline();
1154         }
1155
1156         if (output_preamble) {
1157                 os << "\\end{document}\n";
1158                 texrow().newline();
1159
1160                 lyxerr[Debug::LATEX] << "makeLaTeXFile...done" << endl;
1161         } else {
1162                 lyxerr[Debug::LATEX] << "LaTeXFile for inclusion made."
1163                                      << endl;
1164         }
1165
1166         // Just to be sure. (Asger)
1167         texrow().newline();
1168
1169         lyxerr[Debug::INFO] << "Finished making LaTeX file." << endl;
1170         lyxerr[Debug::INFO] << "Row count was " << texrow().rows() - 1
1171                             << '.' << endl;
1172
1173         // we want this to be true outside previews (for insetexternal)
1174         niceFile() = true;
1175 }
1176
1177
1178 bool Buffer::isLatex() const
1179 {
1180         return params().getLyXTextClass().outputType() == LATEX;
1181 }
1182
1183
1184 bool Buffer::isLinuxDoc() const
1185 {
1186         return params().getLyXTextClass().outputType() == LINUXDOC;
1187 }
1188
1189
1190 bool Buffer::isLiterate() const
1191 {
1192         return params().getLyXTextClass().outputType() == LITERATE;
1193 }
1194
1195
1196 bool Buffer::isDocBook() const
1197 {
1198         return params().getLyXTextClass().outputType() == DOCBOOK;
1199 }
1200
1201
1202 bool Buffer::isSGML() const
1203 {
1204         LyXTextClass const & tclass = params().getLyXTextClass();
1205
1206         return tclass.outputType() == LINUXDOC ||
1207                tclass.outputType() == DOCBOOK;
1208 }
1209
1210
1211 void Buffer::makeLinuxDocFile(string const & fname, bool nice, bool body_only)
1212 {
1213         ofstream ofs;
1214         if (!::openFileWrite(ofs, fname))
1215                 return;
1216
1217         niceFile() = nice; // this will be used by included files.
1218
1219         LaTeXFeatures features(params());
1220
1221         validate(features);
1222
1223         texrow().reset();
1224
1225         LyXTextClass const & tclass = params().getLyXTextClass();
1226
1227         string top_element = tclass.latexname();
1228
1229         if (!body_only) {
1230                 ofs << "<!doctype linuxdoc system";
1231
1232                 string preamble = params().preamble;
1233                 string const name = nice ? ChangeExtension(pimpl_->filename, ".sgml")
1234                          : fname;
1235                 preamble += features.getIncludedFiles(name);
1236                 preamble += features.getLyXSGMLEntities();
1237
1238                 if (!preamble.empty()) {
1239                         ofs << " [ " << preamble << " ]";
1240                 }
1241                 ofs << ">\n\n";
1242
1243                 if (params().options.empty())
1244                         sgml::openTag(ofs, 0, false, top_element);
1245                 else {
1246                         string top = top_element;
1247                         top += ' ';
1248                         top += params().options;
1249                         sgml::openTag(ofs, 0, false, top);
1250                 }
1251         }
1252
1253         ofs << "<!-- LyX "  << lyx_version
1254             << " created this file. For more info see http://www.lyx.org/"
1255             << " -->\n";
1256
1257         Paragraph::depth_type depth = 0; // paragraph depth
1258         string item_name;
1259         vector<string> environment_stack(5);
1260
1261         ParagraphList::iterator pit = paragraphs().begin();
1262         ParagraphList::iterator pend = paragraphs().end();
1263         for (; pit != pend; ++pit) {
1264                 LyXLayout_ptr const & style = pit->layout();
1265                 // treat <toc> as a special case for compatibility with old code
1266                 if (pit->isInset(0)) {
1267                         InsetOld * inset = pit->getInset(0);
1268                         InsetOld::Code lyx_code = inset->lyxCode();
1269                         if (lyx_code == InsetOld::TOC_CODE) {
1270                                 string const temp = "toc";
1271                                 sgml::openTag(ofs, depth, false, temp);
1272                                 continue;
1273                         }
1274                 }
1275
1276                 // environment tag closing
1277                 for (; depth > pit->params().depth(); --depth) {
1278                         sgml::closeTag(ofs, depth, false, environment_stack[depth]);
1279                         environment_stack[depth].erase();
1280                 }
1281
1282                 // write opening SGML tags
1283                 switch (style->latextype) {
1284                 case LATEX_PARAGRAPH:
1285                         if (depth == pit->params().depth()
1286                            && !environment_stack[depth].empty()) {
1287                                 sgml::closeTag(ofs, depth, false, environment_stack[depth]);
1288                                 environment_stack[depth].erase();
1289                                 if (depth)
1290                                         --depth;
1291                                 else
1292                                         ofs << "</p>";
1293                         }
1294                         sgml::openTag(ofs, depth, false, style->latexname());
1295                         break;
1296
1297                 case LATEX_COMMAND:
1298                         if (depth != 0)
1299                                 error(ErrorItem(_("Error:"), _("Wrong depth for LatexType Command.\n"), pit->id(), 0, pit->size()));
1300
1301                         if (!environment_stack[depth].empty()) {
1302                                 sgml::closeTag(ofs, depth, false, environment_stack[depth]);
1303                                 ofs << "</p>";
1304                         }
1305
1306                         environment_stack[depth].erase();
1307                         sgml::openTag(ofs, depth, false, style->latexname());
1308                         break;
1309
1310                 case LATEX_ENVIRONMENT:
1311                 case LATEX_ITEM_ENVIRONMENT:
1312                 case LATEX_BIB_ENVIRONMENT:
1313                 {
1314                         string const & latexname = style->latexname();
1315
1316                         if (depth == pit->params().depth()
1317                             && environment_stack[depth] != latexname) {
1318                                 sgml::closeTag(ofs, depth, false,
1319                                              environment_stack[depth]);
1320                                 environment_stack[depth].erase();
1321                         }
1322                         if (depth < pit->params().depth()) {
1323                                depth = pit->params().depth();
1324                                environment_stack[depth].erase();
1325                         }
1326                         if (environment_stack[depth] != latexname) {
1327                                 if (depth == 0) {
1328                                         sgml::openTag(ofs, depth, false, "p");
1329                                 }
1330                                 sgml::openTag(ofs, depth, false, latexname);
1331
1332                                 if (environment_stack.size() == depth + 1)
1333                                         environment_stack.push_back("!-- --");
1334                                 environment_stack[depth] = latexname;
1335                         }
1336
1337                         if (style->latexparam() == "CDATA")
1338                                 ofs << "<![CDATA[";
1339
1340                         if (style->latextype == LATEX_ENVIRONMENT) break;
1341
1342                         if (style->labeltype == LABEL_MANUAL)
1343                                 item_name = "tag";
1344                         else
1345                                 item_name = "item";
1346
1347                         sgml::openTag(ofs, depth + 1, false, item_name);
1348                 }
1349                 break;
1350
1351                 default:
1352                         sgml::openTag(ofs, depth, false, style->latexname());
1353                         break;
1354                 }
1355
1356                 simpleLinuxDocOnePar(ofs, pit, depth);
1357
1358                 ofs << "\n";
1359                 // write closing SGML tags
1360                 switch (style->latextype) {
1361                 case LATEX_COMMAND:
1362                         break;
1363                 case LATEX_ENVIRONMENT:
1364                 case LATEX_ITEM_ENVIRONMENT:
1365                 case LATEX_BIB_ENVIRONMENT:
1366                         if (style->latexparam() == "CDATA")
1367                                 ofs << "]]>";
1368                         break;
1369                 default:
1370                         sgml::closeTag(ofs, depth, false, style->latexname());
1371                         break;
1372                 }
1373         }
1374
1375         // Close open tags
1376         for (int i = depth; i >= 0; --i)
1377                 sgml::closeTag(ofs, depth, false, environment_stack[i]);
1378
1379         if (!body_only) {
1380                 ofs << "\n\n";
1381                 sgml::closeTag(ofs, 0, false, top_element);
1382         }
1383
1384         ofs.close();
1385         // How to check for successful close
1386
1387         // we want this to be true outside previews (for insetexternal)
1388         niceFile() = true;
1389 }
1390
1391
1392 // checks, if newcol chars should be put into this line
1393 // writes newline, if necessary.
1394 namespace {
1395
1396 void sgmlLineBreak(ostream & os, string::size_type & colcount,
1397                           string::size_type newcol)
1398 {
1399         colcount += newcol;
1400         if (colcount > lyxrc.ascii_linelen) {
1401                 os << "\n";
1402                 colcount = newcol; // assume write after this call
1403         }
1404 }
1405
1406 enum PAR_TAG {
1407         NONE=0,
1408         TT = 1,
1409         SF = 2,
1410         BF = 4,
1411         IT = 8,
1412         SL = 16,
1413         EM = 32
1414 };
1415
1416
1417 string tag_name(PAR_TAG const & pt) {
1418         switch (pt) {
1419         case NONE: return "!-- --";
1420         case TT: return "tt";
1421         case SF: return "sf";
1422         case BF: return "bf";
1423         case IT: return "it";
1424         case SL: return "sl";
1425         case EM: return "em";
1426         }
1427         return "";
1428 }
1429
1430
1431 inline
1432 void operator|=(PAR_TAG & p1, PAR_TAG const & p2)
1433 {
1434         p1 = static_cast<PAR_TAG>(p1 | p2);
1435 }
1436
1437
1438 inline
1439 void reset(PAR_TAG & p1, PAR_TAG const & p2)
1440 {
1441         p1 = static_cast<PAR_TAG>(p1 & ~p2);
1442 }
1443
1444 } // anon
1445
1446
1447 // Handle internal paragraph parsing -- layout already processed.
1448 void Buffer::simpleLinuxDocOnePar(ostream & os,
1449         ParagraphList::iterator par,
1450         Paragraph::depth_type /*depth*/) const
1451 {
1452         LyXLayout_ptr const & style = par->layout();
1453
1454         string::size_type char_line_count = 5;     // Heuristic choice ;-)
1455
1456         // gets paragraph main font
1457         LyXFont font_old;
1458         bool desc_on;
1459         if (style->labeltype == LABEL_MANUAL) {
1460                 font_old = style->labelfont;
1461                 desc_on = true;
1462         } else {
1463                 font_old = style->font;
1464                 desc_on = false;
1465         }
1466
1467         LyXFont::FONT_FAMILY family_type = LyXFont::ROMAN_FAMILY;
1468         LyXFont::FONT_SERIES series_type = LyXFont::MEDIUM_SERIES;
1469         LyXFont::FONT_SHAPE  shape_type  = LyXFont::UP_SHAPE;
1470         bool is_em = false;
1471
1472         stack<PAR_TAG> tag_state;
1473         // parsing main loop
1474         for (pos_type i = 0; i < par->size(); ++i) {
1475
1476                 PAR_TAG tag_close = NONE;
1477                 list < PAR_TAG > tag_open;
1478
1479                 LyXFont const font = par->getFont(params(), i, outerFont(par, paragraphs()));
1480
1481                 if (font_old.family() != font.family()) {
1482                         switch (family_type) {
1483                         case LyXFont::SANS_FAMILY:
1484                                 tag_close |= SF;
1485                                 break;
1486                         case LyXFont::TYPEWRITER_FAMILY:
1487                                 tag_close |= TT;
1488                                 break;
1489                         default:
1490                                 break;
1491                         }
1492
1493                         family_type = font.family();
1494
1495                         switch (family_type) {
1496                         case LyXFont::SANS_FAMILY:
1497                                 tag_open.push_back(SF);
1498                                 break;
1499                         case LyXFont::TYPEWRITER_FAMILY:
1500                                 tag_open.push_back(TT);
1501                                 break;
1502                         default:
1503                                 break;
1504                         }
1505                 }
1506
1507                 if (font_old.series() != font.series()) {
1508                         switch (series_type) {
1509                         case LyXFont::BOLD_SERIES:
1510                                 tag_close |= BF;
1511                                 break;
1512                         default:
1513                                 break;
1514                         }
1515
1516                         series_type = font.series();
1517
1518                         switch (series_type) {
1519                         case LyXFont::BOLD_SERIES:
1520                                 tag_open.push_back(BF);
1521                                 break;
1522                         default:
1523                                 break;
1524                         }
1525
1526                 }
1527
1528                 if (font_old.shape() != font.shape()) {
1529                         switch (shape_type) {
1530                         case LyXFont::ITALIC_SHAPE:
1531                                 tag_close |= IT;
1532                                 break;
1533                         case LyXFont::SLANTED_SHAPE:
1534                                 tag_close |= SL;
1535                                 break;
1536                         default:
1537                                 break;
1538                         }
1539
1540                         shape_type = font.shape();
1541
1542                         switch (shape_type) {
1543                         case LyXFont::ITALIC_SHAPE:
1544                                 tag_open.push_back(IT);
1545                                 break;
1546                         case LyXFont::SLANTED_SHAPE:
1547                                 tag_open.push_back(SL);
1548                                 break;
1549                         default:
1550                                 break;
1551                         }
1552                 }
1553                 // handle <em> tag
1554                 if (font_old.emph() != font.emph()) {
1555                         if (font.emph() == LyXFont::ON) {
1556                                 tag_open.push_back(EM);
1557                                 is_em = true;
1558                         }
1559                         else if (is_em) {
1560                                 tag_close |= EM;
1561                                 is_em = false;
1562                         }
1563                 }
1564
1565                 list < PAR_TAG > temp;
1566                 while (!tag_state.empty() && tag_close) {
1567                         PAR_TAG k =  tag_state.top();
1568                         tag_state.pop();
1569                         os << "</" << tag_name(k) << '>';
1570                         if (tag_close & k)
1571                                 reset(tag_close,k);
1572                         else
1573                                 temp.push_back(k);
1574                 }
1575
1576                 for(list< PAR_TAG >::const_iterator j = temp.begin();
1577                     j != temp.end(); ++j) {
1578                         tag_state.push(*j);
1579                         os << '<' << tag_name(*j) << '>';
1580                 }
1581
1582                 for(list< PAR_TAG >::const_iterator j = tag_open.begin();
1583                     j != tag_open.end(); ++j) {
1584                         tag_state.push(*j);
1585                         os << '<' << tag_name(*j) << '>';
1586                 }
1587
1588                 char c = par->getChar(i);
1589
1590                 if (c == Paragraph::META_INSET) {
1591                         InsetOld * inset = par->getInset(i);
1592                         inset->linuxdoc(*this, os);
1593                         font_old = font;
1594                         continue;
1595                 }
1596
1597                 if (style->latexparam() == "CDATA") {
1598                         // "TeX"-Mode on == > SGML-Mode on.
1599                         if (c != '\0')
1600                                 os << c;
1601                         ++char_line_count;
1602                 } else {
1603                         bool ws;
1604                         string str;
1605                         boost::tie(ws, str) = sgml::escapeChar(c);
1606                         if (ws && !par->isFreeSpacing()) {
1607                                 // in freespacing mode, spaces are
1608                                 // non-breaking characters
1609                                 if (desc_on) {// if char is ' ' then...
1610
1611                                         ++char_line_count;
1612                                         sgmlLineBreak(os, char_line_count, 6);
1613                                         os << "</tag>";
1614                                         desc_on = false;
1615                                 } else  {
1616                                         sgmlLineBreak(os, char_line_count, 1);
1617                                         os << c;
1618                                 }
1619                         } else {
1620                                 os << str;
1621                                 char_line_count += str.length();
1622                         }
1623                 }
1624                 font_old = font;
1625         }
1626
1627         while (!tag_state.empty()) {
1628                 os << "</" << tag_name(tag_state.top()) << '>';
1629                 tag_state.pop();
1630         }
1631
1632         // resets description flag correctly
1633         if (desc_on) {
1634                 // <tag> not closed...
1635                 sgmlLineBreak(os, char_line_count, 6);
1636                 os << "</tag>";
1637         }
1638 }
1639
1640
1641 void Buffer::makeDocBookFile(string const & fname, bool nice, bool only_body)
1642 {
1643         ofstream ofs;
1644         if (!::openFileWrite(ofs, fname))
1645                 return;
1646
1647         niceFile() = nice; // this will be used by Insetincludes.
1648
1649         LaTeXFeatures features(params());
1650         validate(features);
1651
1652         texrow().reset();
1653
1654         LyXTextClass const & tclass = params().getLyXTextClass();
1655         string top_element = tclass.latexname();
1656
1657         if (!only_body) {
1658                 ofs << "<!DOCTYPE " << top_element
1659                     << "  PUBLIC \"-//OASIS//DTD DocBook V4.1//EN\"";
1660
1661                 string preamble = params().preamble;
1662                 string const name = nice ? ChangeExtension(pimpl_->filename, ".sgml")
1663                          : fname;
1664                 preamble += features.getIncludedFiles(name);
1665                 preamble += features.getLyXSGMLEntities();
1666
1667                 if (!preamble.empty()) {
1668                         ofs << "\n [ " << preamble << " ]";
1669                 }
1670                 ofs << ">\n\n";
1671         }
1672
1673         string top = top_element;
1674         top += " lang=\"";
1675         top += params().language->code();
1676         top += '"';
1677
1678         if (!params().options.empty()) {
1679                 top += ' ';
1680                 top += params().options;
1681         }
1682         sgml::openTag(ofs, 0, false, top);
1683
1684         ofs << "<!-- DocBook file was created by LyX " << lyx_version
1685             << "\n  See http://www.lyx.org/ for more information -->\n";
1686
1687         vector<string> environment_stack(10);
1688         vector<string> environment_inner(10);
1689         vector<string> command_stack(10);
1690
1691         bool command_flag = false;
1692         Paragraph::depth_type command_depth = 0;
1693         Paragraph::depth_type command_base = 0;
1694         Paragraph::depth_type cmd_depth = 0;
1695         Paragraph::depth_type depth = 0; // paragraph depth
1696
1697         string item_name;
1698         string command_name;
1699
1700         ParagraphList::iterator par = paragraphs().begin();
1701         ParagraphList::iterator pend = paragraphs().end();
1702
1703         for (; par != pend; ++par) {
1704                 string sgmlparam;
1705                 string c_depth;
1706                 string c_params;
1707                 int desc_on = 0; // description mode
1708
1709                 LyXLayout_ptr const & style = par->layout();
1710
1711                 // environment tag closing
1712                 for (; depth > par->params().depth(); --depth) {
1713                         if (environment_inner[depth] != "!-- --" && !environment_inner[depth].empty()) {
1714                                 item_name = "listitem";
1715                                 sgml::closeTag(ofs, command_depth + depth, false, item_name);
1716                                 if (environment_inner[depth] == "varlistentry")
1717                                         sgml::closeTag(ofs, depth+command_depth, false, environment_inner[depth]);
1718                         }
1719                         sgml::closeTag(ofs, depth + command_depth, false, environment_stack[depth]);
1720                         environment_stack[depth].erase();
1721                         environment_inner[depth].erase();
1722                 }
1723
1724                 if (depth == par->params().depth()
1725                    && environment_stack[depth] != style->latexname()
1726                    && !environment_stack[depth].empty()) {
1727                         if (environment_inner[depth] != "!-- --") {
1728                                 item_name= "listitem";
1729                                 sgml::closeTag(ofs, command_depth+depth, false, item_name);
1730                                 if (environment_inner[depth] == "varlistentry")
1731                                         sgml::closeTag(ofs, depth + command_depth, false, environment_inner[depth]);
1732                         }
1733
1734                         sgml::closeTag(ofs, depth + command_depth, false, environment_stack[depth]);
1735
1736                         environment_stack[depth].erase();
1737                         environment_inner[depth].erase();
1738                 }
1739
1740                 // Write opening SGML tags.
1741                 switch (style->latextype) {
1742                 case LATEX_PARAGRAPH:
1743                         sgml::openTag(ofs, depth + command_depth,
1744                                     false, style->latexname());
1745                         break;
1746
1747                 case LATEX_COMMAND:
1748                         if (depth != 0)
1749                                 error(ErrorItem(_("Error"), _("Wrong depth for LatexType Command."), par->id(), 0, par->size()));
1750
1751                         command_name = style->latexname();
1752
1753                         sgmlparam = style->latexparam();
1754                         c_params = split(sgmlparam, c_depth,'|');
1755
1756                         cmd_depth = atoi(c_depth);
1757
1758                         if (command_flag) {
1759                                 if (cmd_depth < command_base) {
1760                                         for (Paragraph::depth_type j = command_depth;
1761                                              j >= command_base; --j) {
1762                                                 sgml::closeTag(ofs, j, false, command_stack[j]);
1763                                                 ofs << endl;
1764                                         }
1765                                         command_depth = command_base = cmd_depth;
1766                                 } else if (cmd_depth <= command_depth) {
1767                                         for (int j = command_depth;
1768                                              j >= int(cmd_depth); --j) {
1769                                                 sgml::closeTag(ofs, j, false, command_stack[j]);
1770                                                 ofs << endl;
1771                                         }
1772                                         command_depth = cmd_depth;
1773                                 } else
1774                                         command_depth = cmd_depth;
1775                         } else {
1776                                 command_depth = command_base = cmd_depth;
1777                                 command_flag = true;
1778                         }
1779                         if (command_stack.size() == command_depth + 1)
1780                                 command_stack.push_back(string());
1781                         command_stack[command_depth] = command_name;
1782
1783                         // treat label as a special case for
1784                         // more WYSIWYM handling.
1785                         // This is a hack while paragraphs can't have
1786                         // attributes, like id in this case.
1787                         if (par->isInset(0)) {
1788                                 InsetOld * inset = par->getInset(0);
1789                                 InsetOld::Code lyx_code = inset->lyxCode();
1790                                 if (lyx_code == InsetOld::LABEL_CODE) {
1791                                         command_name += " id=\"";
1792                                         command_name += (static_cast<InsetCommand *>(inset))->getContents();
1793                                         command_name += '"';
1794                                         desc_on = 3;
1795                                 }
1796                         }
1797
1798                         sgml::openTag(ofs, depth + command_depth, false, command_name);
1799
1800                         item_name = c_params.empty() ? "title" : c_params;
1801                         sgml::openTag(ofs, depth + 1 + command_depth, false, item_name);
1802                         break;
1803
1804                 case LATEX_ENVIRONMENT:
1805                 case LATEX_ITEM_ENVIRONMENT:
1806                         if (depth < par->params().depth()) {
1807                                 depth = par->params().depth();
1808                                 environment_stack[depth].erase();
1809                         }
1810
1811                         if (environment_stack[depth] != style->latexname()) {
1812                                 if (environment_stack.size() == depth + 1) {
1813                                         environment_stack.push_back("!-- --");
1814                                         environment_inner.push_back("!-- --");
1815                                 }
1816                                 environment_stack[depth] = style->latexname();
1817                                 environment_inner[depth] = "!-- --";
1818                                 sgml::openTag(ofs, depth + command_depth, false, environment_stack[depth]);
1819                         } else {
1820                                 if (environment_inner[depth] != "!-- --") {
1821                                         item_name= "listitem";
1822                                         sgml::closeTag(ofs, command_depth + depth, false, item_name);
1823                                         if (environment_inner[depth] == "varlistentry")
1824                                                 sgml::closeTag(ofs, depth + command_depth, false, environment_inner[depth]);
1825                                 }
1826                         }
1827
1828                         if (style->latextype == LATEX_ENVIRONMENT) {
1829                                 if (!style->latexparam().empty()) {
1830                                         if (style->latexparam() == "CDATA")
1831                                                 ofs << "<![CDATA[";
1832                                         else
1833                                                 sgml::openTag(ofs, depth + command_depth, false, style->latexparam());
1834                                 }
1835                                 break;
1836                         }
1837
1838                         desc_on = (style->labeltype == LABEL_MANUAL);
1839
1840                         environment_inner[depth] = desc_on ? "varlistentry" : "listitem";
1841                         sgml::openTag(ofs, depth + 1 + command_depth,
1842                                     false, environment_inner[depth]);
1843
1844                         item_name = desc_on ? "term" : "para";
1845                         sgml::openTag(ofs, depth + 1 + command_depth,
1846                                     false, item_name);
1847                         break;
1848                 default:
1849                         sgml::openTag(ofs, depth + command_depth,
1850                                     false, style->latexname());
1851                         break;
1852                 }
1853
1854                 simpleDocBookOnePar(ofs, par, desc_on,
1855                                     depth + 1 + command_depth);
1856
1857                 string end_tag;
1858                 // write closing SGML tags
1859                 switch (style->latextype) {
1860                 case LATEX_COMMAND:
1861                         end_tag = c_params.empty() ? "title" : c_params;
1862                         sgml::closeTag(ofs, depth + command_depth,
1863                                      false, end_tag);
1864                         break;
1865                 case LATEX_ENVIRONMENT:
1866                         if (!style->latexparam().empty()) {
1867                                 if (style->latexparam() == "CDATA")
1868                                         ofs << "]]>";
1869                                 else
1870                                         sgml::closeTag(ofs, depth + command_depth, false, style->latexparam());
1871                         }
1872                         break;
1873                 case LATEX_ITEM_ENVIRONMENT:
1874                         if (desc_on == 1) break;
1875                         end_tag = "para";
1876                         sgml::closeTag(ofs, depth + 1 + command_depth, false, end_tag);
1877                         break;
1878                 case LATEX_PARAGRAPH:
1879                         sgml::closeTag(ofs, depth + command_depth, false, style->latexname());
1880                         break;
1881                 default:
1882                         sgml::closeTag(ofs, depth + command_depth, false, style->latexname());
1883                         break;
1884                 }
1885         }
1886
1887         // Close open tags
1888         for (int d = depth; d >= 0; --d) {
1889                 if (!environment_stack[depth].empty()) {
1890                         if (environment_inner[depth] != "!-- --") {
1891                                 item_name = "listitem";
1892                                 sgml::closeTag(ofs, command_depth + depth, false, item_name);
1893                                if (environment_inner[depth] == "varlistentry")
1894                                        sgml::closeTag(ofs, depth + command_depth, false, environment_inner[depth]);
1895                         }
1896
1897                         sgml::closeTag(ofs, depth + command_depth, false, environment_stack[depth]);
1898                 }
1899         }
1900
1901         for (int j = command_depth; j >= 0 ; --j)
1902                 if (!command_stack[j].empty()) {
1903                         sgml::closeTag(ofs, j, false, command_stack[j]);
1904                         ofs << endl;
1905                 }
1906
1907         ofs << "\n\n";
1908         sgml::closeTag(ofs, 0, false, top_element);
1909
1910         ofs.close();
1911         // How to check for successful close
1912
1913         // we want this to be true outside previews (for insetexternal)
1914         niceFile() = true;
1915 }
1916
1917
1918 void Buffer::simpleDocBookOnePar(ostream & os,
1919                                  ParagraphList::iterator par, int & desc_on,
1920                                  Paragraph::depth_type depth) const
1921 {
1922         bool emph_flag = false;
1923
1924         LyXLayout_ptr const & style = par->layout();
1925
1926         LyXFont font_old = (style->labeltype == LABEL_MANUAL ? style->labelfont : style->font);
1927
1928         int char_line_count = depth;
1929         //if (!style.free_spacing)
1930         //      os << string(depth,' ');
1931
1932         // parsing main loop
1933         for (pos_type i = 0; i < par->size(); ++i) {
1934                 LyXFont font = par->getFont(params(), i, outerFont(par, paragraphs()));
1935
1936                 // handle <emphasis> tag
1937                 if (font_old.emph() != font.emph()) {
1938                         if (font.emph() == LyXFont::ON) {
1939                                 if (style->latexparam() == "CDATA")
1940                                         os << "]]>";
1941                                 os << "<emphasis>";
1942                                 if (style->latexparam() == "CDATA")
1943                                         os << "<![CDATA[";
1944                                 emph_flag = true;
1945                         } else if (i) {
1946                                 if (style->latexparam() == "CDATA")
1947                                         os << "]]>";
1948                                 os << "</emphasis>";
1949                                 if (style->latexparam() == "CDATA")
1950                                         os << "<![CDATA[";
1951                                 emph_flag = false;
1952                         }
1953                 }
1954
1955
1956                 if (par->isInset(i)) {
1957                         InsetOld * inset = par->getInset(i);
1958                         // don't print the inset in position 0 if desc_on == 3 (label)
1959                         if (i || desc_on != 3) {
1960                                 if (style->latexparam() == "CDATA")
1961                                         os << "]]>";
1962                                 inset->docbook(*this, os, false);
1963                                 if (style->latexparam() == "CDATA")
1964                                         os << "<![CDATA[";
1965                         }
1966                 } else {
1967                         char c = par->getChar(i);
1968                         bool ws;
1969                         string str;
1970                         boost::tie(ws, str) = sgml::escapeChar(c);
1971
1972                         if (style->pass_thru) {
1973                                 os << c;
1974                         } else if (par->isFreeSpacing() || c != ' ') {
1975                                         os << str;
1976                         } else if (desc_on == 1) {
1977                                 ++char_line_count;
1978                                 os << "\n</term><listitem><para>";
1979                                 desc_on = 2;
1980                         } else {
1981                                 os << ' ';
1982                         }
1983                 }
1984                 font_old = font;
1985         }
1986
1987         if (emph_flag) {
1988                 if (style->latexparam() == "CDATA")
1989                         os << "]]>";
1990                 os << "</emphasis>";
1991                 if (style->latexparam() == "CDATA")
1992                         os << "<![CDATA[";
1993         }
1994
1995         // resets description flag correctly
1996         if (desc_on == 1) {
1997                 // <term> not closed...
1998                 os << "</term>\n<listitem><para>&nbsp;</para>";
1999         }
2000         if (style->free_spacing)
2001                 os << '\n';
2002 }
2003
2004
2005 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
2006 // Other flags: -wall -v0 -x
2007 int Buffer::runChktex()
2008 {
2009         busy(true);
2010
2011         // get LaTeX-Filename
2012         string const name = getLatexName();
2013         string path = filePath();
2014
2015         string const org_path = path;
2016         if (lyxrc.use_tempdir || !IsDirWriteable(path)) {
2017                 path = temppath();
2018         }
2019
2020         Path p(path); // path to LaTeX file
2021         message(_("Running chktex..."));
2022
2023         // Generate the LaTeX file if neccessary
2024         LatexRunParams runparams;
2025         runparams.flavor = LatexRunParams::LATEX;
2026         runparams.nice = false;
2027         makeLaTeXFile(name, org_path, runparams);
2028
2029         TeXErrors terr;
2030         Chktex chktex(lyxrc.chktex_command, name, filePath());
2031         int res = chktex.run(terr); // run chktex
2032
2033         if (res == -1) {
2034                 Alert::error(_("chktex failure"),
2035                              _("Could not run chktex successfully."));
2036         } else if (res > 0) {
2037                 // Insert all errors as errors boxes
2038                 bufferErrors(*this, terr);
2039         }
2040
2041         busy(false);
2042
2043         return res;
2044 }
2045
2046
2047 void Buffer::validate(LaTeXFeatures & features) const
2048 {
2049         LyXTextClass const & tclass = params().getLyXTextClass();
2050
2051         if (params().tracking_changes) {
2052                 features.require("dvipost");
2053                 features.require("color");
2054         }
2055
2056         // AMS Style is at document level
2057         if (params().use_amsmath == BufferParams::AMS_ON
2058             || tclass.provides(LyXTextClass::amsmath))
2059                 features.require("amsmath");
2060
2061         for_each(paragraphs().begin(), paragraphs().end(),
2062                  boost::bind(&Paragraph::validate, _1, boost::ref(features)));
2063
2064         // the bullet shapes are buffer level not paragraph level
2065         // so they are tested here
2066         for (int i = 0; i < 4; ++i) {
2067                 if (params().user_defined_bullet(i) != ITEMIZE_DEFAULTS[i]) {
2068                         int const font = params().user_defined_bullet(i).getFont();
2069                         if (font == 0) {
2070                                 int const c = params()
2071                                         .user_defined_bullet(i)
2072                                         .getCharacter();
2073                                 if (c == 16
2074                                    || c == 17
2075                                    || c == 25
2076                                    || c == 26
2077                                    || c == 31) {
2078                                         features.require("latexsym");
2079                                 }
2080                         } else if (font == 1) {
2081                                 features.require("amssymb");
2082                         } else if ((font >= 2 && font <= 5)) {
2083                                 features.require("pifont");
2084                         }
2085                 }
2086         }
2087
2088         if (lyxerr.debugging(Debug::LATEX)) {
2089                 features.showStruct();
2090         }
2091 }
2092
2093
2094 void Buffer::getLabelList(std::vector<string> & list) const
2095 {
2096         /// if this is a child document and the parent is already loaded
2097         /// Use the parent's list instead  [ale990407]
2098         if (!params().parentname.empty()
2099             && bufferlist.exists(params().parentname)) {
2100                 Buffer const * tmp = bufferlist.getBuffer(params().parentname);
2101                 if (tmp) {
2102                         tmp->getLabelList(list);
2103                         return;
2104                 }
2105         }
2106
2107         for (inset_iterator it = inset_const_iterator_begin();
2108              it != inset_const_iterator_end(); ++it) {
2109                 it->getLabelList(list);
2110         }
2111 }
2112
2113
2114 // This is also a buffer property (ale)
2115 void Buffer::fillWithBibKeys(std::vector<std::pair<string, string> > & keys) const
2116 {
2117         /// if this is a child document and the parent is already loaded
2118         /// use the parent's list instead  [ale990412]
2119         if (!params().parentname.empty() &&
2120             bufferlist.exists(params().parentname)) {
2121                 Buffer const * tmp = bufferlist.getBuffer(params().parentname);
2122                 if (tmp) {
2123                         tmp->fillWithBibKeys(keys);
2124                         return;
2125                 }
2126         }
2127
2128         for (inset_iterator it = inset_const_iterator_begin();
2129                 it != inset_const_iterator_end(); ++it) {
2130                 if (it->lyxCode() == InsetOld::BIBTEX_CODE)
2131                         static_cast<InsetBibtex &>(*it).fillWithBibKeys(*this, keys);
2132                 else if (it->lyxCode() == InsetOld::INCLUDE_CODE)
2133                         static_cast<InsetInclude &>(*it).fillWithBibKeys(keys);
2134                 else if (it->lyxCode() == InsetOld::BIBITEM_CODE) {
2135                         InsetBibitem & bib = static_cast<InsetBibitem &>(*it);
2136                         string const key = bib.getContents();
2137                         string const opt = bib.getOptions();
2138                         string const ref; // = pit->asString(this, false);
2139                         string const info = opt + "TheBibliographyRef" + ref;
2140                         keys.push_back(pair<string, string>(key, info));
2141                 }
2142         }
2143 }
2144
2145
2146 bool Buffer::isDepClean(string const & name) const
2147 {
2148         DepClean::const_iterator it = pimpl_->dep_clean.find(name);
2149         if (it == pimpl_->dep_clean.end())
2150                 return true;
2151         return it->second;
2152 }
2153
2154
2155 void Buffer::markDepClean(string const & name)
2156 {
2157         pimpl_->dep_clean[name] = true;
2158 }
2159
2160
2161 bool Buffer::dispatch(string const & command, bool * result)
2162 {
2163         // Split command string into command and argument
2164         string cmd;
2165         string line = ltrim(command);
2166         string const arg = trim(split(line, cmd, ' '));
2167
2168         return dispatch(lyxaction.LookupFunc(cmd), arg, result);
2169 }
2170
2171
2172 bool Buffer::dispatch(int action, string const & argument, bool * result)
2173 {
2174         bool dispatched = true;
2175
2176         switch (action) {
2177                 case LFUN_EXPORT: {
2178                         bool const tmp = Exporter::Export(this, argument, false);
2179                         if (result)
2180                                 *result = tmp;
2181                         break;
2182                 }
2183
2184                 default:
2185                         dispatched = false;
2186         }
2187         return dispatched;
2188 }
2189
2190
2191 void Buffer::changeLanguage(Language const * from, Language const * to)
2192 {
2193         lyxerr << "Changing Language!" << endl;
2194
2195         // Take care of l10n/i18n
2196         updateDocLang(to);
2197
2198         ParIterator end = par_iterator_end();
2199         for (ParIterator it = par_iterator_begin(); it != end; ++it)
2200                 it->changeLanguage(params(), from, to);
2201 }
2202
2203
2204 void Buffer::updateDocLang(Language const * nlang)
2205 {
2206         pimpl_->messages.reset(new Messages(nlang->code()));
2207 }
2208
2209
2210 bool Buffer::isMultiLingual()
2211 {
2212         ParIterator end = par_iterator_end();
2213         for (ParIterator it = par_iterator_begin(); it != end; ++it)
2214                 if (it->isMultiLingual(params()))
2215                         return true;
2216
2217         return false;
2218 }
2219
2220
2221 void Buffer::inset_iterator::setParagraph()
2222 {
2223         while (pit != pend) {
2224                 it = pit->insetlist.begin();
2225                 if (it != pit->insetlist.end())
2226                         return;
2227                 ++pit;
2228         }
2229 }
2230
2231
2232 InsetOld * Buffer::getInsetFromID(int id_arg) const
2233 {
2234         for (inset_iterator it = inset_const_iterator_begin();
2235                  it != inset_const_iterator_end(); ++it)
2236         {
2237                 if (it->id() == id_arg)
2238                         return &(*it);
2239                 InsetOld * in = it->getInsetFromID(id_arg);
2240                 if (in)
2241                         return in;
2242         }
2243         return 0;
2244 }
2245
2246
2247 ParIterator Buffer::getParFromID(int id) const
2248 {
2249 #warning FIXME: const correctness! (Andre)
2250         ParIterator it = const_cast<Buffer*>(this)->par_iterator_begin();
2251         ParIterator end = const_cast<Buffer*>(this)->par_iterator_end();
2252
2253 #warning FIXME, perhaps this func should return a ParIterator? (Lgb)
2254         if (id < 0) {
2255                 // John says this is called with id == -1 from undo
2256                 lyxerr << "getParFromID(), id: " << id << endl;
2257                 return end;
2258         }
2259
2260         for (; it != end; ++it)
2261                 if (it->id() == id)
2262                         return it;
2263
2264         return end;
2265 }
2266
2267
2268 bool Buffer::hasParWithID(int id) const
2269 {
2270         ParConstIterator it = par_iterator_begin();
2271         ParConstIterator end = par_iterator_end();
2272
2273         if (id < 0) {
2274                 // John says this is called with id == -1 from undo
2275                 lyxerr << "hasParWithID(), id: " << id << endl;
2276                 return 0;
2277         }
2278
2279         for (; it != end; ++it)
2280                 if (it->id() == id)
2281                         return true;
2282
2283         return false;
2284 }
2285
2286
2287 ParIterator Buffer::par_iterator_begin()
2288 {
2289         return ParIterator(paragraphs().begin(), paragraphs());
2290 }
2291
2292
2293 ParIterator Buffer::par_iterator_end()
2294 {
2295         return ParIterator(paragraphs().end(), paragraphs());
2296 }
2297
2298
2299 ParConstIterator Buffer::par_iterator_begin() const
2300 {
2301         ParagraphList const & pars = paragraphs();
2302         return ParConstIterator(const_cast<ParagraphList&>(pars).begin(), pars);
2303 }
2304
2305
2306 ParConstIterator Buffer::par_iterator_end() const
2307 {
2308         ParagraphList const & pars = paragraphs();
2309         return ParConstIterator(const_cast<ParagraphList&>(pars).end(), pars);
2310 }
2311
2312
2313 Language const * Buffer::getLanguage() const
2314 {
2315         return params().language;
2316 }
2317
2318
2319 string const Buffer::B_(string const & l10n) const
2320 {
2321         if (pimpl_->messages.get()) {
2322                 return pimpl_->messages->get(l10n);
2323         }
2324
2325         return _(l10n);
2326 }
2327
2328
2329 bool Buffer::isClean() const
2330 {
2331         return pimpl_->lyx_clean;
2332 }
2333
2334
2335 bool Buffer::isBakClean() const
2336 {
2337         return pimpl_->bak_clean;
2338 }
2339
2340
2341 void Buffer::markClean() const
2342 {
2343         if (!pimpl_->lyx_clean) {
2344                 pimpl_->lyx_clean = true;
2345                 updateTitles();
2346         }
2347         // if the .lyx file has been saved, we don't need an
2348         // autosave
2349         pimpl_->bak_clean = true;
2350 }
2351
2352
2353 void Buffer::markBakClean()
2354 {
2355         pimpl_->bak_clean = true;
2356 }
2357
2358
2359 void Buffer::setUnnamed(bool flag)
2360 {
2361         pimpl_->unnamed = flag;
2362 }
2363
2364
2365 bool Buffer::isUnnamed()
2366 {
2367         return pimpl_->unnamed;
2368 }
2369
2370
2371 void Buffer::markDirty()
2372 {
2373         if (pimpl_->lyx_clean) {
2374                 pimpl_->lyx_clean = false;
2375                 updateTitles();
2376         }
2377         pimpl_->bak_clean = false;
2378
2379         DepClean::iterator it = pimpl_->dep_clean.begin();
2380         DepClean::const_iterator const end = pimpl_->dep_clean.end();
2381
2382         for (; it != end; ++it) {
2383                 it->second = false;
2384         }
2385 }
2386
2387
2388 string const & Buffer::fileName() const
2389 {
2390         return pimpl_->filename;
2391 }
2392
2393
2394 string const & Buffer::filePath() const
2395 {
2396         return pimpl_->filepath;
2397 }
2398
2399
2400 bool Buffer::isReadonly() const
2401 {
2402         return pimpl_->read_only;
2403 }
2404
2405
2406 void Buffer::setParentName(string const & name)
2407 {
2408         params().parentname = name;
2409 }
2410
2411
2412 Buffer::inset_iterator::inset_iterator()
2413         : pit(), pend()
2414 {}
2415
2416
2417 Buffer::inset_iterator::inset_iterator(base_type p, base_type e)
2418         : pit(p), pend(e)
2419 {
2420         setParagraph();
2421 }
2422
2423
2424 Buffer::inset_iterator Buffer::inset_iterator_begin()
2425 {
2426         return inset_iterator(paragraphs().begin(), paragraphs().end());
2427 }
2428
2429
2430 Buffer::inset_iterator Buffer::inset_iterator_end()
2431 {
2432         return inset_iterator(paragraphs().end(), paragraphs().end());
2433 }
2434
2435
2436 Buffer::inset_iterator Buffer::inset_const_iterator_begin() const
2437 {
2438         ParagraphList & pars = const_cast<ParagraphList&>(paragraphs());
2439         return inset_iterator(pars.begin(), pars.end());
2440 }
2441
2442
2443 Buffer::inset_iterator Buffer::inset_const_iterator_end() const
2444 {
2445         ParagraphList & pars = const_cast<ParagraphList&>(paragraphs());
2446         return inset_iterator(pars.end(), pars.end());
2447 }
2448
2449
2450 Buffer::inset_iterator & Buffer::inset_iterator::operator++()
2451 {
2452         if (pit != pend) {
2453                 ++it;
2454                 if (it == pit->insetlist.end()) {
2455                         ++pit;
2456                         setParagraph();
2457                 }
2458         }
2459         return *this;
2460 }
2461
2462
2463 Buffer::inset_iterator Buffer::inset_iterator::operator++(int)
2464 {
2465         inset_iterator tmp = *this;
2466         ++*this;
2467         return tmp;
2468 }
2469
2470
2471 Buffer::inset_iterator::reference Buffer::inset_iterator::operator*()
2472 {
2473         return *it->inset;
2474 }
2475
2476
2477 Buffer::inset_iterator::pointer Buffer::inset_iterator::operator->()
2478 {
2479         return it->inset;
2480 }
2481
2482
2483 ParagraphList::iterator Buffer::inset_iterator::getPar() const
2484 {
2485         return pit;
2486 }
2487
2488
2489 lyx::pos_type Buffer::inset_iterator::getPos() const
2490 {
2491         return it->pos;
2492 }
2493
2494
2495 bool operator==(Buffer::inset_iterator const & iter1,
2496                 Buffer::inset_iterator const & iter2)
2497 {
2498         return iter1.pit == iter2.pit
2499                 && (iter1.pit == iter1.pend || iter1.it == iter2.it);
2500 }
2501
2502
2503 bool operator!=(Buffer::inset_iterator const & iter1,
2504                 Buffer::inset_iterator const & iter2)
2505 {
2506         return !(iter1 == iter2);
2507 }