]> git.lyx.org Git - lyx.git/blob - src/buffer.C
more cursor dispatch
[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 "counters.h"
20 #include "Bullet.h"
21 #include "Chktex.h"
22 #include "debug.h"
23 #include "errorlist.h"
24 #include "exporter.h"
25 #include "format.h"
26 #include "funcrequest.h"
27 #include "gettext.h"
28 #include "iterators.h"
29 #include "language.h"
30 #include "LaTeX.h"
31 #include "LaTeXFeatures.h"
32 #include "LyXAction.h"
33 #include "lyxlex.h"
34 #include "lyxtext.h"
35 #include "lyxrc.h"
36 #include "lyxvc.h"
37 #include "messages.h"
38 #include "output.h"
39 #include "output_docbook.h"
40 #include "output_latex.h"
41 #include "output_linuxdoc.h"
42 #include "paragraph.h"
43 #include "paragraph_funcs.h"
44 #include "ParagraphParameters.h"
45 #include "PosIterator.h"
46 #include "sgml.h"
47 #include "texrow.h"
48 #include "undo.h"
49 #include "version.h"
50
51 #include "insets/insetbibitem.h"
52 #include "insets/insetbibtex.h"
53 #include "insets/insetinclude.h"
54 #include "insets/insettext.h"
55
56 #include "frontends/Alert.h"
57
58 #include "graphics/Previews.h"
59
60 #include "support/FileInfo.h"
61 #include "support/filetools.h"
62 #include "support/gzstream.h"
63 #include "support/lyxlib.h"
64 #include "support/os.h"
65 #include "support/path.h"
66 #include "support/textutils.h"
67 #include "support/tostr.h"
68
69 #include <boost/bind.hpp>
70
71 #include "support/std_sstream.h"
72
73 #include <iomanip>
74 #include <stack>
75
76 #include <utime.h>
77
78 #ifdef HAVE_LOCALE
79 #endif
80
81 using lyx::pos_type;
82
83 using lyx::support::AddName;
84 using lyx::support::atoi;
85 using lyx::support::bformat;
86 using lyx::support::ChangeExtension;
87 using lyx::support::cmd_ret;
88 using lyx::support::CreateBufferTmpDir;
89 using lyx::support::destroyDir;
90 using lyx::support::FileInfo;
91 using lyx::support::FileInfo;
92 using lyx::support::getExtFromContents;
93 using lyx::support::IsDirWriteable;
94 using lyx::support::IsFileWriteable;
95 using lyx::support::LibFileSearch;
96 using lyx::support::ltrim;
97 using lyx::support::MakeAbsPath;
98 using lyx::support::MakeDisplayPath;
99 using lyx::support::MakeLatexName;
100 using lyx::support::OnlyFilename;
101 using lyx::support::OnlyPath;
102 using lyx::support::Path;
103 using lyx::support::QuoteName;
104 using lyx::support::removeAutosaveFile;
105 using lyx::support::rename;
106 using lyx::support::RunCommand;
107 using lyx::support::split;
108 using lyx::support::strToInt;
109 using lyx::support::subst;
110 using lyx::support::tempName;
111 using lyx::support::trim;
112
113 namespace os = lyx::support::os;
114
115 using std::endl;
116 using std::for_each;
117 using std::make_pair;
118
119 using std::ifstream;
120 using std::ios;
121 using std::ostream;
122 using std::ostringstream;
123 using std::ofstream;
124 using std::pair;
125 using std::stack;
126 using std::vector;
127 using std::string;
128
129
130 // all these externs should eventually be removed.
131 extern BufferList bufferlist;
132
133 namespace {
134
135 const int LYX_FORMAT = 229;
136
137 } // namespace anon
138
139
140 typedef std::map<string, bool> DepClean;
141
142 struct Buffer::Impl
143 {
144         Impl(Buffer & parent, string const & file, bool readonly);
145
146         limited_stack<Undo> undostack;
147         limited_stack<Undo> redostack;
148         BufferParams params;
149         LyXVC lyxvc;
150         string temppath;
151         TexRow texrow;
152
153         /// need to regenerate .tex ?
154         DepClean dep_clean;
155
156         /// is save needed
157         mutable bool lyx_clean;
158
159         /// is autosave needed
160         mutable bool bak_clean;
161
162         /// is this a unnamed file (New...)
163         bool unnamed;
164
165         /// buffer is r/o
166         bool read_only;
167
168         /// name of the file the buffer is associated with.
169         string filename;
170
171         /// The path to the document file.
172         string filepath;
173
174         boost::scoped_ptr<Messages> messages;
175
176         /** set to true only when the file is fully loaded.
177          *  Used to prevent the premature generation of previews
178          *  and by the citation inset.
179          */
180         bool file_fully_loaded;
181
182         /// our Text
183         LyXText text;
184 };
185
186
187 Buffer::Impl::Impl(Buffer & parent, string const & file, bool readonly_)
188         : lyx_clean(true), bak_clean(true), unnamed(false), read_only(readonly_),
189           filename(file), filepath(OnlyPath(file)), file_fully_loaded(false),
190                 text(0, 0)
191 {
192         lyxvc.buffer(&parent);
193         if (readonly_ || lyxrc.use_tempdir)
194                 temppath = CreateBufferTmpDir();
195 }
196
197
198 Buffer::Buffer(string const & file, bool ronly)
199         : pimpl_(new Impl(*this, file, ronly))
200 {
201         lyxerr[Debug::INFO] << "Buffer::Buffer()" << endl;
202 }
203
204
205 Buffer::~Buffer()
206 {
207         lyxerr[Debug::INFO] << "Buffer::~Buffer()" << endl;
208         // here the buffer should take care that it is
209         // saved properly, before it goes into the void.
210
211         closing();
212
213         if (!temppath().empty() && destroyDir(temppath()) != 0) {
214                 Alert::warning(_("Could not remove temporary directory"),
215                         bformat(_("Could not remove the temporary directory %1$s"), temppath()));
216         }
217
218         // Remove any previewed LaTeX snippets associated with this buffer.
219         lyx::graphics::Previews::get().removeLoader(*this);
220 }
221
222
223 LyXText & Buffer::text() const
224 {
225         return const_cast<LyXText &>(pimpl_->text);
226 }
227
228
229 limited_stack<Undo> & Buffer::undostack()
230 {
231         return pimpl_->undostack;
232 }
233
234
235 limited_stack<Undo> const & Buffer::undostack() const
236 {
237         return pimpl_->undostack;
238 }
239
240
241 limited_stack<Undo> & Buffer::redostack()
242 {
243         return pimpl_->redostack;
244 }
245
246
247 limited_stack<Undo> const & Buffer::redostack() const
248 {
249         return pimpl_->redostack;
250 }
251
252
253 BufferParams & Buffer::params()
254 {
255         return pimpl_->params;
256 }
257
258
259 BufferParams const & Buffer::params() const
260 {
261         return pimpl_->params;
262 }
263
264
265 ParagraphList & Buffer::paragraphs()
266 {
267         return pimpl_->text.paragraphs();
268 }
269
270
271 ParagraphList const & Buffer::paragraphs() const
272 {
273         return pimpl_->text.paragraphs();
274 }
275
276
277 LyXVC & Buffer::lyxvc()
278 {
279         return pimpl_->lyxvc;
280 }
281
282
283 LyXVC const & Buffer::lyxvc() const
284 {
285         return pimpl_->lyxvc;
286 }
287
288
289 string const & Buffer::temppath() const
290 {
291         return pimpl_->temppath;
292 }
293
294
295 TexRow & Buffer::texrow()
296 {
297         return pimpl_->texrow;
298 }
299
300
301 TexRow const & Buffer::texrow() const
302 {
303         return pimpl_->texrow;
304 }
305
306
307 string const Buffer::getLatexName(bool no_path) const
308 {
309         string const name = ChangeExtension(MakeLatexName(fileName()), ".tex");
310         return no_path ? OnlyFilename(name) : name;
311 }
312
313
314 pair<Buffer::LogType, string> const Buffer::getLogName() const
315 {
316         string const filename = getLatexName(false);
317
318         if (filename.empty())
319                 return make_pair(Buffer::latexlog, string());
320
321         string path = OnlyPath(filename);
322
323         if (lyxrc.use_tempdir || !IsDirWriteable(path))
324                 path = temppath();
325
326         string const fname = AddName(path,
327                                      OnlyFilename(ChangeExtension(filename,
328                                                                   ".log")));
329         string const bname =
330                 AddName(path, OnlyFilename(
331                         ChangeExtension(filename,
332                                         formats.extension("literate") + ".out")));
333
334         // If no Latex log or Build log is newer, show Build log
335
336         FileInfo const f_fi(fname);
337         FileInfo const b_fi(bname);
338
339         if (b_fi.exist() &&
340             (!f_fi.exist() || f_fi.getModificationTime() < b_fi.getModificationTime())) {
341                 lyxerr[Debug::FILES] << "Log name calculated as: " << bname << endl;
342                 return make_pair(Buffer::buildlog, bname);
343         }
344         lyxerr[Debug::FILES] << "Log name calculated as: " << fname << endl;
345         return make_pair(Buffer::latexlog, fname);
346 }
347
348
349 void Buffer::setReadonly(bool flag)
350 {
351         if (pimpl_->read_only != flag) {
352                 pimpl_->read_only = flag;
353                 readonly(flag);
354         }
355 }
356
357
358 void Buffer::setFileName(string const & newfile)
359 {
360         pimpl_->filename = MakeAbsPath(newfile);
361         pimpl_->filepath = OnlyPath(pimpl_->filename);
362         setReadonly(IsFileWriteable(pimpl_->filename) == 0);
363         updateTitles();
364 }
365
366
367 // We'll remove this later. (Lgb)
368 namespace {
369
370 void unknownClass(string const & unknown)
371 {
372         Alert::warning(_("Unknown document class"),
373                 bformat(_("Using the default document class, because the "
374                         "class %1$s is unknown."), unknown));
375 }
376
377 } // anon
378
379
380 int Buffer::readHeader(LyXLex & lex)
381 {
382         int unknown_tokens = 0;
383
384         while (lex.isOK()) {
385                 lex.nextToken();
386                 string const token = lex.getString();
387
388                 if (token.empty())
389                         continue;
390
391                 if (token == "\\end_header")
392                         break;
393
394                 lyxerr[Debug::PARSER] << "Handling header token: `"
395                                       << token << '\'' << endl;
396
397
398                 string unknown = params().readToken(lex, token);
399                 if (!unknown.empty()) {
400                         if (unknown[0] != '\\') {
401                                 unknownClass(unknown);
402                         } else {
403                                 ++unknown_tokens;
404                                 string const s = bformat(_("Unknown token: "
405                                                            "%1$s %2$s\n"),
406                                                          token,
407                                                          lex.getString());
408                                 error(ErrorItem(_("Header error"), s,
409                                                 -1, 0, 0));
410                         }
411                 }
412         }
413         return unknown_tokens;
414 }
415
416
417 // candidate for move to BufferView
418 // (at least some parts in the beginning of the func)
419 //
420 // Uwe C. Schroeder
421 // changed to be public and have one parameter
422 // if par = 0 normal behavior
423 // else insert behavior
424 // Returns false if "\end_document" is not read (Asger)
425 bool Buffer::readBody(LyXLex & lex)
426 {
427         bool the_end_read = false;
428
429         if (paragraphs().empty()) {
430                 readHeader(lex);
431                 if (!params().getLyXTextClass().load()) {
432                         string theclass = params().getLyXTextClass().name();
433                         Alert::error(_("Can't load document class"), bformat(
434                                         "Using the default document class, because the "
435                                         " class %1$s could not be loaded.", theclass));
436                         params().textclass = 0;
437                 }
438         } else {
439                 // We don't want to adopt the parameters from the
440                 // document we insert, so read them into a temporary buffer
441                 // and then discard it
442
443                 Buffer tmpbuf("", false);
444                 tmpbuf.readHeader(lex);
445         }
446
447         if (text().read(*this, lex))
448                 the_end_read = true;
449
450         return the_end_read;
451 }
452
453
454 // needed to insert the selection
455 void Buffer::insertStringAsLines(ParagraphList::iterator & par, pos_type & pos,
456                                  LyXFont const & fn, string const & str)
457 {
458         LyXLayout_ptr const & layout = par->layout();
459
460         LyXFont font = fn;
461
462         par->checkInsertChar(font);
463         // insert the string, don't insert doublespace
464         bool space_inserted = true;
465         bool autobreakrows = !par->inInset() ||
466                 static_cast<InsetText *>(par->inInset())->getAutoBreakRows();
467         for(string::const_iterator cit = str.begin();
468             cit != str.end(); ++cit) {
469                 if (*cit == '\n') {
470                         if (autobreakrows && (!par->empty() || par->allowEmpty())) {
471                                 breakParagraph(params(), paragraphs(), par, pos,
472                                                layout->isEnvironment());
473                                 ++par;
474                                 pos = 0;
475                                 space_inserted = true;
476                         } else {
477                                 continue;
478                         }
479                         // do not insert consecutive spaces if !free_spacing
480                 } else if ((*cit == ' ' || *cit == '\t') &&
481                            space_inserted && !par->isFreeSpacing()) {
482                         continue;
483                 } else if (*cit == '\t') {
484                         if (!par->isFreeSpacing()) {
485                                 // tabs are like spaces here
486                                 par->insertChar(pos, ' ', font);
487                                 ++pos;
488                                 space_inserted = true;
489                         } else {
490                                 const pos_type nb = 8 - pos % 8;
491                                 for (pos_type a = 0; a < nb ; ++a) {
492                                         par->insertChar(pos, ' ', font);
493                                         ++pos;
494                                 }
495                                 space_inserted = true;
496                         }
497                 } else if (!IsPrintable(*cit)) {
498                         // Ignore unprintables
499                         continue;
500                 } else {
501                         // just insert the character
502                         par->insertChar(pos, *cit, font);
503                         ++pos;
504                         space_inserted = (*cit == ' ');
505                 }
506
507         }
508 }
509
510
511 bool Buffer::readFile(string const & filename)
512 {
513         // Check if the file is compressed.
514         string const format = getExtFromContents(filename);
515         if (format == "gzip" || format == "zip" || format == "compress") {
516                 params().compressed = true;
517         }
518
519         bool ret = readFile(filename, paragraphs().begin());
520
521         // After we have read a file, we must ensure that the buffer
522         // language is set and used in the gui.
523         // If you know of a better place to put this, please tell me. (Lgb)
524         updateDocLang(params().language);
525
526         return ret;
527 }
528
529
530 bool Buffer::readFile(string const & filename, ParagraphList::iterator pit)
531 {
532         LyXLex lex(0, 0);
533         lex.setFile(filename);
534
535         return readFile(lex, filename, pit);
536 }
537
538
539 bool Buffer::fully_loaded() const
540 {
541         return pimpl_->file_fully_loaded;
542 }
543
544
545 void Buffer::fully_loaded(bool value)
546 {
547         pimpl_->file_fully_loaded = value;
548 }
549
550
551 bool Buffer::readFile(LyXLex & lex, string const & filename,
552                       ParagraphList::iterator pit)
553 {
554         BOOST_ASSERT(!filename.empty());
555
556         if (!lex.isOK()) {
557                 Alert::error(_("Document could not be read"),
558                              bformat(_("%1$s could not be read."), filename));
559                 return false;
560         }
561
562         lex.next();
563         string const token(lex.getString());
564
565         if (!lex.isOK()) {
566                 Alert::error(_("Document could not be read"),
567                              bformat(_("%1$s could not be read."), filename));
568                 return false;
569         }
570
571         // the first token _must_ be...
572         if (token != "\\lyxformat") {
573                 lyxerr << "Token: " << token << endl;
574
575                 Alert::error(_("Document format failure"),
576                              bformat(_("%1$s is not a LyX document."),
577                                        filename));
578                 return false;
579         }
580
581         lex.eatLine();
582         string tmp_format = lex.getString();
583         //lyxerr << "LyX Format: `" << tmp_format << '\'' << endl;
584         // if present remove ".," from string.
585         string::size_type dot = tmp_format.find_first_of(".,");
586         //lyxerr << "           dot found at " << dot << endl;
587         if (dot != string::npos)
588                         tmp_format.erase(dot, 1);
589         int file_format = strToInt(tmp_format);
590         //lyxerr << "format: " << file_format << endl;
591
592         if (file_format > LYX_FORMAT) {
593                 Alert::warning(_("Document format failure"),
594                                bformat(_("%1$s was created with a newer"
595                                          " version of LyX. This is likely to"
596                                          " cause problems."),
597                                          filename));
598         } else if (file_format < LYX_FORMAT) {
599                 string const tmpfile = tempName();
600                 string command = LibFileSearch("lyx2lyx", "lyx2lyx");
601                 if (command.empty()) {
602                         Alert::error(_("Conversion script not found"),
603                                      bformat(_("%1$s is from an earlier"
604                                                " version of LyX, but the"
605                                                " conversion script lyx2lyx"
606                                                " could not be found."),
607                                                filename));
608                         return false;
609                 }
610                 command += " -t"
611                         + tostr(LYX_FORMAT)
612                         + " -o " + tmpfile + ' '
613                         + QuoteName(filename);
614                 lyxerr[Debug::INFO] << "Running '"
615                                     << command << '\''
616                                     << endl;
617                 cmd_ret const ret = RunCommand(command);
618                 if (ret.first != 0) {
619                         Alert::error(_("Conversion script failed"),
620                                      bformat(_("%1$s is from an earlier version"
621                                               " of LyX, but the lyx2lyx script"
622                                               " failed to convert it."),
623                                               filename));
624                         return false;
625                 } else {
626                         bool ret = readFile(tmpfile, pit);
627                         // Do stuff with tmpfile name and buffer name here.
628                         return ret;
629                 }
630
631         }
632
633         bool the_end = readBody(lex);
634         params().setPaperStuff();
635
636         if (!the_end) {
637                 Alert::error(_("Document format failure"),
638                              bformat(_("%1$s ended unexpectedly, which means"
639                                        " that it is probably corrupted."),
640                                        filename));
641         }
642         pimpl_->file_fully_loaded = true;
643         return true;
644 }
645
646
647 // Should probably be moved to somewhere else: BufferView? LyXView?
648 bool Buffer::save() const
649 {
650         // We don't need autosaves in the immediate future. (Asger)
651         resetAutosaveTimers();
652
653         // make a backup
654         string s;
655         if (lyxrc.make_backup) {
656                 s = fileName() + '~';
657                 if (!lyxrc.backupdir_path.empty())
658                         s = AddName(lyxrc.backupdir_path,
659                                     subst(os::slashify_path(s),'/','!'));
660
661                 // Rename is the wrong way of making a backup,
662                 // this is the correct way.
663                 /* truss cp fil fil2:
664                    lstat("LyXVC3.lyx", 0xEFFFF898)                 Err#2 ENOENT
665                    stat("LyXVC.lyx", 0xEFFFF688)                   = 0
666                    open("LyXVC.lyx", O_RDONLY)                     = 3
667                    open("LyXVC3.lyx", O_WRONLY|O_CREAT|O_TRUNC, 0600) = 4
668                    fstat(4, 0xEFFFF508)                            = 0
669                    fstat(3, 0xEFFFF508)                            = 0
670                    read(3, " # T h i s   f i l e   w".., 8192)     = 5579
671                    write(4, " # T h i s   f i l e   w".., 5579)    = 5579
672                    read(3, 0xEFFFD4A0, 8192)                       = 0
673                    close(4)                                        = 0
674                    close(3)                                        = 0
675                    chmod("LyXVC3.lyx", 0100644)                    = 0
676                    lseek(0, 0, SEEK_CUR)                           = 46440
677                    _exit(0)
678                 */
679
680                 // Should probably have some more error checking here.
681                 // Doing it this way, also makes the inodes stay the same.
682                 // This is still not a very good solution, in particular we
683                 // might loose the owner of the backup.
684                 FileInfo finfo(fileName());
685                 if (finfo.exist()) {
686                         mode_t fmode = finfo.getMode();
687                         struct utimbuf times = {
688                                 finfo.getAccessTime(),
689                                 finfo.getModificationTime() };
690
691                         ifstream ifs(fileName().c_str());
692                         ofstream ofs(s.c_str(), ios::out|ios::trunc);
693                         if (ifs && ofs) {
694                                 ofs << ifs.rdbuf();
695                                 ifs.close();
696                                 ofs.close();
697                                 ::chmod(s.c_str(), fmode);
698
699                                 if (::utime(s.c_str(), &times)) {
700                                         lyxerr << "utime error." << endl;
701                                 }
702                         } else {
703                                 lyxerr << "LyX was not able to make "
704                                         "backup copy. Beware." << endl;
705                         }
706                 }
707         }
708
709         if (writeFile(fileName())) {
710                 markClean();
711                 removeAutosaveFile(fileName());
712         } else {
713                 // Saving failed, so backup is not backup
714                 if (lyxrc.make_backup) {
715                         rename(s, fileName());
716                 }
717                 return false;
718         }
719         return true;
720 }
721
722
723 bool Buffer::writeFile(string const & fname) const
724 {
725         if (pimpl_->read_only && (fname == fileName())) {
726                 return false;
727         }
728
729         FileInfo finfo(fname);
730         if (finfo.exist() && !finfo.writable()) {
731                 return false;
732         }
733
734         bool retval;
735
736         if (params().compressed) {
737                 gz::ogzstream ofs(fname.c_str());
738
739                 if (!ofs)
740                         return false;
741
742                 retval = do_writeFile(ofs);
743
744         } else {
745                 ofstream ofs(fname.c_str());
746                 if (!ofs)
747                         return false;
748
749                 retval = do_writeFile(ofs);
750         }
751
752         return retval;
753 }
754
755
756 bool Buffer::do_writeFile(ostream & ofs) const
757 {
758
759 #ifdef HAVE_LOCALE
760         // Use the standard "C" locale for file output.
761         ofs.imbue(std::locale::classic());
762 #endif
763
764         // The top of the file should not be written by params().
765
766         // write out a comment in the top of the file
767         ofs << "#LyX " << lyx_version
768             << " created this file. For more info see http://www.lyx.org/\n"
769             << "\\lyxformat " << LYX_FORMAT << "\n";
770
771         // now write out the buffer parameters.
772         params().writeFile(ofs);
773
774         ofs << "\\end_header\n";
775
776         // write the text
777         text().write(*this, ofs);
778
779         // Write marker that shows file is complete
780         ofs << "\n\\end_document" << endl;
781
782         // Shouldn't really be needed....
783         //ofs.close();
784
785         // how to check if close went ok?
786         // Following is an attempt... (BE 20001011)
787
788         // good() returns false if any error occured, including some
789         //        formatting error.
790         // bad()  returns true if something bad happened in the buffer,
791         //        which should include file system full errors.
792
793         bool status = true;
794         if (!ofs.good()) {
795                 status = false;
796 #if 0
797                 if (ofs.bad()) {
798                         lyxerr << "Buffer::writeFile: BAD ERROR!" << endl;
799                 } else {
800                         lyxerr << "Buffer::writeFile: NOT SO BAD ERROR!"
801                                << endl;
802                 }
803 #endif
804         }
805
806         return status;
807 }
808
809
810 void Buffer::makeLaTeXFile(string const & fname,
811                            string const & original_path,
812                            OutputParams const & runparams,
813                            bool output_preamble, bool output_body)
814 {
815         lyxerr[Debug::LATEX] << "makeLaTeXFile..." << endl;
816
817         ofstream ofs;
818         if (!openFileWrite(ofs, fname))
819                 return;
820
821         makeLaTeXFile(ofs, original_path,
822                       runparams, output_preamble, output_body);
823
824         ofs.close();
825         if (ofs.fail()) {
826                 lyxerr << "File was not closed properly." << endl;
827         }
828 }
829
830
831 void Buffer::makeLaTeXFile(ostream & os,
832                            string const & original_path,
833                            OutputParams const & runparams_in,
834                            bool output_preamble, bool output_body)
835 {
836         OutputParams runparams = runparams_in;
837
838         // validate the buffer.
839         lyxerr[Debug::LATEX] << "  Validating buffer..." << endl;
840         LaTeXFeatures features(*this, params(), runparams.nice);
841         validate(features);
842         lyxerr[Debug::LATEX] << "  Buffer validation done." << endl;
843
844         texrow().reset();
845         // The starting paragraph of the coming rows is the
846         // first paragraph of the document. (Asger)
847         texrow().start(paragraphs().begin()->id(), 0);
848
849         if (output_preamble && runparams.nice) {
850                 os << "%% LyX " << lyx_version << " created this file.  "
851                         "For more info, see http://www.lyx.org/.\n"
852                         "%% Do not edit unless you really know what "
853                         "you are doing.\n";
854                 texrow().newline();
855                 texrow().newline();
856         }
857         lyxerr[Debug::INFO] << "lyx header finished" << endl;
858         // There are a few differences between nice LaTeX and usual files:
859         // usual is \batchmode and has a
860         // special input@path to allow the including of figures
861         // with either \input or \includegraphics (what figinsets do).
862         // input@path is set when the actual parameter
863         // original_path is set. This is done for usual tex-file, but not
864         // for nice-latex-file. (Matthias 250696)
865         if (output_preamble) {
866                 if (!runparams.nice) {
867                         // code for usual, NOT nice-latex-file
868                         os << "\\batchmode\n"; // changed
869                         // from \nonstopmode
870                         texrow().newline();
871                 }
872                 if (!original_path.empty()) {
873                         string inputpath = os::external_path(original_path);
874                         subst(inputpath, "~", "\\string~");
875                         os << "\\makeatletter\n"
876                             << "\\def\\input@path{{"
877                             << inputpath << "/}}\n"
878                             << "\\makeatother\n";
879                         texrow().newline();
880                         texrow().newline();
881                         texrow().newline();
882                 }
883
884                 // Write the preamble
885                 runparams.use_babel = params().writeLaTeX(os, features, texrow());
886
887                 if (!output_body)
888                         return;
889
890                 // make the body.
891                 os << "\\begin{document}\n";
892                 texrow().newline();
893         } // output_preamble
894         lyxerr[Debug::INFO] << "preamble finished, now the body." << endl;
895
896         if (!lyxrc.language_auto_begin) {
897                 os << subst(lyxrc.language_command_begin, "$$lang",
898                              params().language->babel())
899                     << endl;
900                 texrow().newline();
901         }
902
903         latexParagraphs(*this, paragraphs(), os, texrow(), runparams);
904
905         // add this just in case after all the paragraphs
906         os << endl;
907         texrow().newline();
908
909         if (!lyxrc.language_auto_end) {
910                 os << subst(lyxrc.language_command_end, "$$lang",
911                              params().language->babel())
912                     << endl;
913                 texrow().newline();
914         }
915
916         if (output_preamble) {
917                 os << "\\end{document}\n";
918                 texrow().newline();
919
920                 lyxerr[Debug::LATEX] << "makeLaTeXFile...done" << endl;
921         } else {
922                 lyxerr[Debug::LATEX] << "LaTeXFile for inclusion made."
923                                      << endl;
924         }
925
926         // Just to be sure. (Asger)
927         texrow().newline();
928
929         lyxerr[Debug::INFO] << "Finished making LaTeX file." << endl;
930         lyxerr[Debug::INFO] << "Row count was " << texrow().rows() - 1
931                             << '.' << endl;
932 }
933
934
935 bool Buffer::isLatex() const
936 {
937         return params().getLyXTextClass().outputType() == LATEX;
938 }
939
940
941 bool Buffer::isLinuxDoc() const
942 {
943         return params().getLyXTextClass().outputType() == LINUXDOC;
944 }
945
946
947 bool Buffer::isLiterate() const
948 {
949         return params().getLyXTextClass().outputType() == LITERATE;
950 }
951
952
953 bool Buffer::isDocBook() const
954 {
955         return params().getLyXTextClass().outputType() == DOCBOOK;
956 }
957
958
959 bool Buffer::isSGML() const
960 {
961         LyXTextClass const & tclass = params().getLyXTextClass();
962
963         return tclass.outputType() == LINUXDOC ||
964                tclass.outputType() == DOCBOOK;
965 }
966
967
968 void Buffer::makeLinuxDocFile(string const & fname,
969                               OutputParams const & runparams,
970                               bool body_only )
971 {
972         ofstream ofs;
973         if (!openFileWrite(ofs, fname))
974                 return;
975
976         LaTeXFeatures features(*this, params(), runparams.nice);
977         validate(features);
978
979         texrow().reset();
980
981         LyXTextClass const & tclass = params().getLyXTextClass();
982
983         string top_element = tclass.latexname();
984
985         if (!body_only) {
986                 ofs << tclass.class_header();
987
988                 string preamble = params().preamble;
989                 string const name = runparams.nice ? ChangeExtension(pimpl_->filename, ".sgml")
990                          : fname;
991                 preamble += features.getIncludedFiles(name);
992                 preamble += features.getLyXSGMLEntities();
993
994                 if (!preamble.empty()) {
995                         ofs << " [ " << preamble << " ]";
996                 }
997                 ofs << ">\n\n";
998
999                 if (params().options.empty())
1000                         sgml::openTag(ofs, 0, false, top_element);
1001                 else {
1002                         string top = top_element;
1003                         top += ' ';
1004                         top += params().options;
1005                         sgml::openTag(ofs, 0, false, top);
1006                 }
1007         }
1008
1009         ofs << "<!-- LyX "  << lyx_version
1010             << " created this file. For more info see http://www.lyx.org/"
1011             << " -->\n";
1012
1013         linuxdocParagraphs(*this, paragraphs(), ofs, runparams);
1014
1015         if (!body_only) {
1016                 ofs << "\n\n";
1017                 sgml::closeTag(ofs, 0, false, top_element);
1018         }
1019
1020         ofs.close();
1021         // How to check for successful close
1022 }
1023
1024
1025 void Buffer::makeDocBookFile(string const & fname,
1026                              OutputParams const & runparams,
1027                              bool only_body)
1028 {
1029         ofstream ofs;
1030         if (!openFileWrite(ofs, fname))
1031                 return;
1032
1033         LaTeXFeatures features(*this, params(), runparams.nice);
1034         validate(features);
1035
1036         texrow().reset();
1037
1038         LyXTextClass const & tclass = params().getLyXTextClass();
1039         string top_element = tclass.latexname();
1040
1041         if (!only_body) {
1042                 ofs << subst(tclass.class_header(), "#", top_element);
1043
1044                 string preamble = params().preamble;
1045                 string const name = runparams.nice ? ChangeExtension(pimpl_->filename, ".sgml")
1046                          : fname;
1047                 preamble += features.getIncludedFiles(name);
1048                 preamble += features.getLyXSGMLEntities();
1049
1050                 if (!preamble.empty()) {
1051                         ofs << "\n [ " << preamble << " ]";
1052                 }
1053                 ofs << ">\n\n";
1054         }
1055
1056         string top = top_element;
1057         top += " lang=\"";
1058         top += params().language->code();
1059         top += '"';
1060
1061         if (!params().options.empty()) {
1062                 top += ' ';
1063                 top += params().options;
1064         }
1065         sgml::openTag(ofs, 0, false, top);
1066
1067         ofs << "<!-- SGML/XML file was created by LyX " << lyx_version
1068             << "\n  See http://www.lyx.org/ for more information -->\n";
1069
1070         params().getLyXTextClass().counters().reset();
1071         docbookParagraphs(*this, paragraphs(), ofs, runparams);
1072
1073         ofs << "\n\n";
1074         sgml::closeTag(ofs, 0, false, top_element);
1075
1076         ofs.close();
1077         // How to check for successful close
1078 }
1079
1080
1081 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1082 // Other flags: -wall -v0 -x
1083 int Buffer::runChktex()
1084 {
1085         busy(true);
1086
1087         // get LaTeX-Filename
1088         string const name = getLatexName();
1089         string path = filePath();
1090
1091         string const org_path = path;
1092         if (lyxrc.use_tempdir || !IsDirWriteable(path)) {
1093                 path = temppath();
1094         }
1095
1096         Path p(path); // path to LaTeX file
1097         message(_("Running chktex..."));
1098
1099         // Generate the LaTeX file if neccessary
1100         OutputParams runparams;
1101         runparams.flavor = OutputParams::LATEX;
1102         runparams.nice = false;
1103         makeLaTeXFile(name, org_path, runparams);
1104
1105         TeXErrors terr;
1106         Chktex chktex(lyxrc.chktex_command, name, filePath());
1107         int res = chktex.run(terr); // run chktex
1108
1109         if (res == -1) {
1110                 Alert::error(_("chktex failure"),
1111                              _("Could not run chktex successfully."));
1112         } else if (res > 0) {
1113                 // Insert all errors as errors boxes
1114                 bufferErrors(*this, terr);
1115         }
1116
1117         busy(false);
1118
1119         return res;
1120 }
1121
1122
1123 void Buffer::validate(LaTeXFeatures & features) const
1124 {
1125         LyXTextClass const & tclass = params().getLyXTextClass();
1126
1127         if (params().tracking_changes) {
1128                 features.require("dvipost");
1129                 features.require("color");
1130         }
1131
1132         // AMS Style is at document level
1133         if (params().use_amsmath == BufferParams::AMS_ON
1134             || tclass.provides(LyXTextClass::amsmath))
1135                 features.require("amsmath");
1136
1137         for_each(paragraphs().begin(), paragraphs().end(),
1138                  boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1139
1140         // the bullet shapes are buffer level not paragraph level
1141         // so they are tested here
1142         for (int i = 0; i < 4; ++i) {
1143                 if (params().user_defined_bullet(i) != ITEMIZE_DEFAULTS[i]) {
1144                         int const font = params().user_defined_bullet(i).getFont();
1145                         if (font == 0) {
1146                                 int const c = params()
1147                                         .user_defined_bullet(i)
1148                                         .getCharacter();
1149                                 if (c == 16
1150                                    || c == 17
1151                                    || c == 25
1152                                    || c == 26
1153                                    || c == 31) {
1154                                         features.require("latexsym");
1155                                 }
1156                         } else if (font == 1) {
1157                                 features.require("amssymb");
1158                         } else if ((font >= 2 && font <= 5)) {
1159                                 features.require("pifont");
1160                         }
1161                 }
1162         }
1163
1164         if (lyxerr.debugging(Debug::LATEX)) {
1165                 features.showStruct();
1166         }
1167 }
1168
1169
1170 void Buffer::getLabelList(std::vector<string> & list) const
1171 {
1172         /// if this is a child document and the parent is already loaded
1173         /// Use the parent's list instead  [ale990407]
1174         if (!params().parentname.empty()
1175             && bufferlist.exists(params().parentname)) {
1176                 Buffer const * tmp = bufferlist.getBuffer(params().parentname);
1177                 if (tmp) {
1178                         tmp->getLabelList(list);
1179                         return;
1180                 }
1181         }
1182
1183         for (inset_iterator it = inset_const_iterator_begin();
1184              it != inset_const_iterator_end(); ++it) {
1185                 it->getLabelList(*this, list);
1186         }
1187 }
1188
1189
1190 // This is also a buffer property (ale)
1191 void Buffer::fillWithBibKeys(std::vector<std::pair<string, string> > & keys)
1192         const
1193 {
1194         /// if this is a child document and the parent is already loaded
1195         /// use the parent's list instead  [ale990412]
1196         if (!params().parentname.empty() &&
1197             bufferlist.exists(params().parentname)) {
1198                 Buffer const * tmp = bufferlist.getBuffer(params().parentname);
1199                 if (tmp) {
1200                         tmp->fillWithBibKeys(keys);
1201                         return;
1202                 }
1203         }
1204
1205         for (inset_iterator it = inset_const_iterator_begin();
1206                 it != inset_const_iterator_end(); ++it) {
1207                 if (it->lyxCode() == InsetOld::BIBTEX_CODE) {
1208                         InsetBibtex const & inset =
1209                                 dynamic_cast<InsetBibtex const &>(*it);
1210                         inset.fillWithBibKeys(*this, keys);
1211                 } else if (it->lyxCode() == InsetOld::INCLUDE_CODE) {
1212                         InsetInclude const & inset =
1213                                 dynamic_cast<InsetInclude const &>(*it);
1214                         inset.fillWithBibKeys(*this, keys);
1215                 } else if (it->lyxCode() == InsetOld::BIBITEM_CODE) {
1216                         InsetBibitem const & inset =
1217                                 dynamic_cast<InsetBibitem const &>(*it);
1218                         string const key = inset.getContents();
1219                         string const opt = inset.getOptions();
1220                         string const ref; // = pit->asString(this, false);
1221                         string const info = opt + "TheBibliographyRef" + ref;
1222                         keys.push_back(pair<string, string>(key, info));
1223                 }
1224         }
1225 }
1226
1227
1228 bool Buffer::isDepClean(string const & name) const
1229 {
1230         DepClean::const_iterator it = pimpl_->dep_clean.find(name);
1231         if (it == pimpl_->dep_clean.end())
1232                 return true;
1233         return it->second;
1234 }
1235
1236
1237 void Buffer::markDepClean(string const & name)
1238 {
1239         pimpl_->dep_clean[name] = true;
1240 }
1241
1242
1243 bool Buffer::dispatch(string const & command, bool * result)
1244 {
1245         return dispatch(lyxaction.lookupFunc(command), result);
1246 }
1247
1248
1249 bool Buffer::dispatch(FuncRequest const & func, bool * result)
1250 {
1251         bool dispatched = true;
1252
1253         switch (func.action) {
1254                 case LFUN_EXPORT: {
1255                         bool const tmp = Exporter::Export(this, func.argument, false);
1256                         if (result)
1257                                 *result = tmp;
1258                         break;
1259                 }
1260
1261                 default:
1262                         dispatched = false;
1263         }
1264         return dispatched;
1265 }
1266
1267
1268 void Buffer::changeLanguage(Language const * from, Language const * to)
1269 {
1270         lyxerr << "Changing Language!" << endl;
1271
1272         // Take care of l10n/i18n
1273         updateDocLang(to);
1274
1275         ParIterator end = par_iterator_end();
1276         for (ParIterator it = par_iterator_begin(); it != end; ++it)
1277                 it->changeLanguage(params(), from, to);
1278 }
1279
1280
1281 void Buffer::updateDocLang(Language const * nlang)
1282 {
1283         pimpl_->messages.reset(new Messages(nlang->code()));
1284 }
1285
1286
1287 bool Buffer::isMultiLingual()
1288 {
1289         ParIterator end = par_iterator_end();
1290         for (ParIterator it = par_iterator_begin(); it != end; ++it)
1291                 if (it->isMultiLingual(params()))
1292                         return true;
1293
1294         return false;
1295 }
1296
1297
1298 void Buffer::inset_iterator::setParagraph()
1299 {
1300         while (pit != pend) {
1301                 it = pit->insetlist.begin();
1302                 if (it != pit->insetlist.end())
1303                         return;
1304                 ++pit;
1305         }
1306 }
1307
1308
1309 ParIterator Buffer::getParFromID(int id) const
1310 {
1311 #warning FIXME: const correctness! (Andre)
1312         ParIterator it = const_cast<Buffer*>(this)->par_iterator_begin();
1313         ParIterator end = const_cast<Buffer*>(this)->par_iterator_end();
1314
1315 #warning FIXME, perhaps this func should return a ParIterator? (Lgb)
1316         if (id < 0) {
1317                 // John says this is called with id == -1 from undo
1318                 lyxerr << "getParFromID(), id: " << id << endl;
1319                 return end;
1320         }
1321
1322         for (; it != end; ++it)
1323                 if (it->id() == id)
1324                         return it;
1325
1326         return end;
1327 }
1328
1329
1330 bool Buffer::hasParWithID(int id) const
1331 {
1332         ParConstIterator it = par_iterator_begin();
1333         ParConstIterator end = par_iterator_end();
1334
1335         if (id < 0) {
1336                 // John says this is called with id == -1 from undo
1337                 lyxerr << "hasParWithID(), id: " << id << endl;
1338                 return 0;
1339         }
1340
1341         for (; it != end; ++it)
1342                 if (it->id() == id)
1343                         return true;
1344
1345         return false;
1346 }
1347
1348
1349 PosIterator Buffer::pos_iterator_begin()
1350 {
1351         return PosIterator(&paragraphs(), paragraphs().begin(), 0);
1352 }
1353
1354
1355 PosIterator Buffer::pos_iterator_end()
1356 {
1357         return PosIterator(&paragraphs(), paragraphs().end(), 0);
1358 }
1359
1360
1361 ParIterator Buffer::par_iterator_begin()
1362 {
1363         return ParIterator(paragraphs().begin(), paragraphs());
1364 }
1365
1366
1367 ParIterator Buffer::par_iterator_end()
1368 {
1369         return ParIterator(paragraphs().end(), paragraphs());
1370 }
1371
1372
1373 ParConstIterator Buffer::par_iterator_begin() const
1374 {
1375         ParagraphList const & pars = paragraphs();
1376         return ParConstIterator(const_cast<ParagraphList&>(pars).begin(), pars);
1377 }
1378
1379
1380 ParConstIterator Buffer::par_iterator_end() const
1381 {
1382         ParagraphList const & pars = paragraphs();
1383         return ParConstIterator(const_cast<ParagraphList&>(pars).end(), pars);
1384 }
1385
1386
1387 Language const * Buffer::getLanguage() const
1388 {
1389         return params().language;
1390 }
1391
1392
1393 string const Buffer::B_(string const & l10n) const
1394 {
1395         if (pimpl_->messages.get()) {
1396                 return pimpl_->messages->get(l10n);
1397         }
1398
1399         return _(l10n);
1400 }
1401
1402
1403 bool Buffer::isClean() const
1404 {
1405         return pimpl_->lyx_clean;
1406 }
1407
1408
1409 bool Buffer::isBakClean() const
1410 {
1411         return pimpl_->bak_clean;
1412 }
1413
1414
1415 void Buffer::markClean() const
1416 {
1417         if (!pimpl_->lyx_clean) {
1418                 pimpl_->lyx_clean = true;
1419                 updateTitles();
1420         }
1421         // if the .lyx file has been saved, we don't need an
1422         // autosave
1423         pimpl_->bak_clean = true;
1424 }
1425
1426
1427 void Buffer::markBakClean()
1428 {
1429         pimpl_->bak_clean = true;
1430 }
1431
1432
1433 void Buffer::setUnnamed(bool flag)
1434 {
1435         pimpl_->unnamed = flag;
1436 }
1437
1438
1439 bool Buffer::isUnnamed()
1440 {
1441         return pimpl_->unnamed;
1442 }
1443
1444
1445 void Buffer::markDirty()
1446 {
1447         if (pimpl_->lyx_clean) {
1448                 pimpl_->lyx_clean = false;
1449                 updateTitles();
1450         }
1451         pimpl_->bak_clean = false;
1452
1453         DepClean::iterator it = pimpl_->dep_clean.begin();
1454         DepClean::const_iterator const end = pimpl_->dep_clean.end();
1455
1456         for (; it != end; ++it) {
1457                 it->second = false;
1458         }
1459 }
1460
1461
1462 string const & Buffer::fileName() const
1463 {
1464         return pimpl_->filename;
1465 }
1466
1467
1468 string const & Buffer::filePath() const
1469 {
1470         return pimpl_->filepath;
1471 }
1472
1473
1474 bool Buffer::isReadonly() const
1475 {
1476         return pimpl_->read_only;
1477 }
1478
1479
1480 void Buffer::setParentName(string const & name)
1481 {
1482         params().parentname = name;
1483 }
1484
1485
1486 Buffer::inset_iterator::inset_iterator()
1487         : pit(), pend()
1488 {}
1489
1490
1491 Buffer::inset_iterator::inset_iterator(base_type p, base_type e)
1492         : pit(p), pend(e)
1493 {
1494         setParagraph();
1495 }
1496
1497
1498 Buffer::inset_iterator Buffer::inset_iterator_begin()
1499 {
1500         return inset_iterator(paragraphs().begin(), paragraphs().end());
1501 }
1502
1503
1504 Buffer::inset_iterator Buffer::inset_iterator_end()
1505 {
1506         return inset_iterator(paragraphs().end(), paragraphs().end());
1507 }
1508
1509
1510 Buffer::inset_iterator Buffer::inset_const_iterator_begin() const
1511 {
1512         ParagraphList & pars = const_cast<ParagraphList&>(paragraphs());
1513         return inset_iterator(pars.begin(), pars.end());
1514 }
1515
1516
1517 Buffer::inset_iterator Buffer::inset_const_iterator_end() const
1518 {
1519         ParagraphList & pars = const_cast<ParagraphList&>(paragraphs());
1520         return inset_iterator(pars.end(), pars.end());
1521 }
1522
1523
1524 Buffer::inset_iterator & Buffer::inset_iterator::operator++()
1525 {
1526         if (pit != pend) {
1527                 ++it;
1528                 if (it == pit->insetlist.end()) {
1529                         ++pit;
1530                         setParagraph();
1531                 }
1532         }
1533         return *this;
1534 }
1535
1536
1537 Buffer::inset_iterator Buffer::inset_iterator::operator++(int)
1538 {
1539         inset_iterator tmp = *this;
1540         ++*this;
1541         return tmp;
1542 }
1543
1544
1545 Buffer::inset_iterator::reference Buffer::inset_iterator::operator*()
1546 {
1547         return *it->inset;
1548 }
1549
1550
1551 Buffer::inset_iterator::pointer Buffer::inset_iterator::operator->()
1552 {
1553         return it->inset;
1554 }
1555
1556
1557 ParagraphList::iterator Buffer::inset_iterator::getPar() const
1558 {
1559         return pit;
1560 }
1561
1562
1563 lyx::pos_type Buffer::inset_iterator::getPos() const
1564 {
1565         return it->pos;
1566 }
1567
1568
1569 bool operator==(Buffer::inset_iterator const & iter1,
1570                 Buffer::inset_iterator const & iter2)
1571 {
1572         return iter1.pit == iter2.pit
1573                 && (iter1.pit == iter1.pend || iter1.it == iter2.it);
1574 }
1575
1576
1577 bool operator!=(Buffer::inset_iterator const & iter1,
1578                 Buffer::inset_iterator const & iter2)
1579 {
1580         return !(iter1 == iter2);
1581 }