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