]> git.lyx.org Git - features.git/blob - src/Buffer.h
Detach Buffer preview and update preview in a new thread. Only for Qt4.4 users. This...
[features.git] / src / Buffer.h
1 // -*- C++ -*-
2 /**
3  * \file Buffer.h
4  * This file is part of LyX, the document processor.
5  * Licence details can be found in the file COPYING.
6  *
7  * \author Lars Gullik Bjønnes
8  *
9  * Full author contact details are available in file CREDITS.
10  */
11
12 #ifndef BUFFER_H
13 #define BUFFER_H
14
15 #include "update_flags.h"
16
17 #include "insets/InsetCode.h"
18
19 #include "support/strfwd.h"
20 #include "support/types.h"
21 #include "support/SignalSlot.h"
22
23 #include <list>
24 #include <set>
25 #include <string>
26 #include <vector>
27
28
29 namespace lyx {
30
31 class BiblioInfo;
32 class BufferParams;
33 class BufferSet;
34 class DispatchResult;
35 class DocIterator;
36 class docstring_list;
37 class ErrorItem;
38 class ErrorList;
39 class FuncRequest;
40 class FuncStatus;
41 class Inset;
42 class InsetRef;
43 class InsetLabel;
44 class Font;
45 class Format;
46 class Lexer;
47 class LyXRC;
48 class Text;
49 class LyXVC;
50 class LaTeXFeatures;
51 class Language;
52 class MacroData;
53 class MacroNameSet;
54 class MacroSet;
55 class OutputParams;
56 class Paragraph;
57 class ParConstIterator;
58 class ParIterator;
59 class ParagraphList;
60 class TeXErrors;
61 class TexRow;
62 class TocBackend;
63 class Undo;
64 class WordLangTuple;
65
66 namespace frontend {
67 class GuiBufferDelegate;
68 class WorkAreaManager;
69 }
70
71 namespace support {
72 class FileName;
73 class FileNameList;
74 }
75
76 /** The buffer object.
77  * This is the buffer object. It contains all the informations about
78  * a document loaded into LyX.
79  * The buffer object owns the Text (wrapped in an InsetText), which
80  * contains the individual paragraphs of the document.
81  *
82  *
83  * I am not sure if the class is complete or
84  * minimal, probably not.
85  * \author Lars Gullik Bjønnes
86  */
87 class Buffer {
88 public:
89         /// What type of log will \c getLogName() return?
90         enum LogType {
91                 latexlog, ///< LaTeX log
92                 buildlog  ///< Literate build log
93         };
94
95         /// Result of \c readFile()
96         enum ReadStatus {
97                 failure, ///< The file could not be read
98                 success, ///< The file could not be read
99                 wrongversion ///< The version of the file does not match ours
100         };
101
102
103         /// Method to check if a file is externally modified, used by
104         /// isExternallyModified()
105         /**
106          * timestamp is fast but inaccurate. For example, the granularity
107          * of timestamp on a FAT filesystem is 2 second. Also, various operations
108          * may touch the timestamp of a file even when its content is unchanged.
109          *
110          * checksum is accurate but slow, which can be a problem when it is
111          * frequently used, or used for a large file on a slow (network) file
112          * system.
113          *
114          * FIXME: replace this method with support/FileMonitor.
115          */
116         enum CheckMethod {
117                 checksum_method,  ///< Use file checksum
118                 timestamp_method, ///< Use timestamp, and checksum if timestamp has changed
119         };
120
121         ///
122         enum UpdateScope {
123                 UpdateMaster,
124                 UpdateChildOnly
125         };
126
127         /// Constructor
128         explicit Buffer(std::string const & file, bool readonly = false,
129                 Buffer const * cloned_buffer = 0);
130
131         /// Destructor
132         ~Buffer();
133
134         ///
135         Buffer * clone() const;
136
137         /** High-level interface to buffer functionality.
138             This function parses a command string and executes it.
139         */
140         void dispatch(std::string const & command, DispatchResult & result);
141
142         /// Maybe we know the function already by number...
143         void dispatch(FuncRequest const & func, DispatchResult & result);
144
145         /// Can this function be exectued?
146         /// \return true if we made a decision
147         bool getStatus(FuncRequest const & cmd, FuncStatus & flag);
148
149         /// read a new document from a string
150         bool readString(std::string const &);
151         /// load a new file
152         bool readFile(support::FileName const & filename);
153
154         /// read the header, returns number of unknown tokens
155         int readHeader(Lexer & lex);
156
157         /** Reads a file without header.
158             \param par if != 0 insert the file.
159             \return \c true if file is not completely read.
160         */
161         bool readDocument(Lexer &);
162
163         ///
164         DocIterator getParFromID(int id) const;
165         /// do we have a paragraph with this id?
166         bool hasParWithID(int id) const;
167
168         ///
169         frontend::WorkAreaManager & workAreaManager() const;
170
171         /** Save file.
172             Takes care of auto-save files and backup file if requested.
173             Returns \c true if the save is successful, \c false otherwise.
174         */
175         bool save() const;
176
177         /// Write document to stream. Returns \c false if unsuccesful.
178         bool write(std::ostream &) const;
179         /// save emergency file
180         /// \return a status message towards the user.
181         docstring emergencyWrite();
182         /// Write file. Returns \c false if unsuccesful.
183         bool writeFile(support::FileName const &) const;
184
185         /// Loads LyX file \c filename into buffer, *  and return success
186         bool loadLyXFile(support::FileName const & s);
187
188         /// Fill in the ErrorList with the TeXErrors
189         void bufferErrors(TeXErrors const &, ErrorList &) const;
190
191         /// Just a wrapper for writeLaTeXSource, first creating the ofstream.
192         bool makeLaTeXFile(support::FileName const & filename,
193                            std::string const & original_path,
194                            OutputParams const &,
195                            bool output_preamble = true,
196                            bool output_body = true) const;
197         /** Export the buffer to LaTeX.
198             If \p os is a file stream, and params().inputenc is "auto" or
199             "default", and the buffer contains text in different languages
200             with more than one encoding, then this method will change the
201             encoding associated to \p os. Therefore you must not call this
202             method with a string stream if the output is supposed to go to a
203             file. \code
204             ofdocstream ofs;
205             ofs.open("test.tex");
206             writeLaTeXSource(ofs, ...);
207             ofs.close();
208             \endcode is NOT equivalent to \code
209             odocstringstream oss;
210             writeLaTeXSource(oss, ...);
211             ofdocstream ofs;
212             ofs.open("test.tex");
213             ofs << oss.str();
214             ofs.close();
215             \endcode
216          */
217         void writeLaTeXSource(odocstream & os,
218                            std::string const & original_path,
219                            OutputParams const &,
220                            bool output_preamble = true,
221                            bool output_body = true) const;
222         ///
223         void makeDocBookFile(support::FileName const & filename,
224                              OutputParams const & runparams_in,
225                              bool only_body = false) const;
226         ///
227         void writeDocBookSource(odocstream & os, std::string const & filename,
228                              OutputParams const & runparams_in,
229                              bool only_body = false) const;
230         ///
231         void makeLyXHTMLFile(support::FileName const & filename,
232                              OutputParams const & runparams_in,
233                              bool only_body = false) const;
234         ///
235         void writeLyXHTMLSource(odocstream & os,
236                              OutputParams const & runparams_in,
237                              bool only_body = false) const;
238         /// returns the main language for the buffer (document)
239         Language const * language() const;
240         /// get l10n translated to the buffers language
241         docstring const B_(std::string const & l10n) const;
242
243         ///
244         int runChktex();
245         /// return true if the main lyx file does not need saving
246         bool isClean() const;
247         ///
248         bool isBakClean() const;
249         ///
250         bool isDepClean(std::string const & name) const;
251
252         /// whether or not disk file has been externally modified
253         bool isExternallyModified(CheckMethod method) const;
254
255         /// save timestamp and checksum of the given file.
256         void saveCheckSum(support::FileName const & file) const;
257
258         /// mark the main lyx file as not needing saving
259         void markClean() const;
260
261         ///
262         void markBakClean() const;
263
264         ///
265         void markDepClean(std::string const & name);
266
267         ///
268         void setUnnamed(bool flag = true);
269
270         /// Whether or not a filename has been assigned to this buffer
271         bool isUnnamed() const;
272
273         /// Whether or not this buffer is internal.
274         ///
275         /// An internal buffer does not contain a real document, but some auxiliary text segment.
276         /// It is not associated with a filename, it is never saved, thus it does not need to be
277         /// automatically saved, nor it needs to trigger any "do you want to save ?" question.
278         bool isInternal() const;
279
280         /// Mark this buffer as dirty.
281         void markDirty();
282
283         /// Returns the buffer's filename. It is always an absolute path.
284         support::FileName fileName() const;
285
286         /// Returns the buffer's filename. It is always an absolute path.
287         std::string absFileName() const;
288
289         /// Returns the the path where the buffer lives.
290         /// It is always an absolute path.
291         std::string filePath() const;
292
293         /** A transformed version of the file name, adequate for LaTeX.
294             \param no_path optional if \c true then the path is stripped.
295         */
296         std::string latexName(bool no_path = true) const;
297
298         /// Get the name and type of the log.
299         std::string logName(LogType * type = 0) const;
300
301         /// Change name of buffer. Updates "read-only" flag.
302         void setFileName(std::string const & newfile);
303
304         /// Set document's parent Buffer.
305         void setParent(Buffer const *);
306         Buffer const * parent() const;
307
308         // Collect all relative buffer
309         std::vector<Buffer const *> allRelatives() const;
310
311         /** Get the document's master (or \c this if this is not a
312             child document)
313          */
314         Buffer const * masterBuffer() const;
315
316         /// \return true if \p child is a child of this \c Buffer.
317         bool isChild(Buffer * child) const;
318         
319         /// return a vector with all children (and grandchildren)
320         std::vector<Buffer *> getChildren(bool grand_children = true) const;
321
322         /// Is buffer read-only?
323         bool isReadonly() const;
324
325         /// Set buffer read-only flag
326         void setReadonly(bool flag = true);
327
328         /// returns \c true if the buffer contains a LaTeX document
329         bool isLatex() const;
330         /// returns \c true if the buffer contains a DocBook document
331         bool isDocBook() const;
332         /// returns \c true if the buffer contains a Wed document
333         bool isLiterate() const;
334
335         /** Validate a buffer for LaTeX.
336             This validates the buffer, and returns a struct for use by
337             #makeLaTeX# and others. Its main use is to figure out what
338             commands and packages need to be included in the LaTeX file.
339             It (should) also check that the needed constructs are there
340             (i.e. that the \refs points to coresponding \labels). It
341             should perhaps inset "error" insets to help the user correct
342             obvious mistakes.
343         */
344         void validate(LaTeXFeatures &) const;
345
346         /// Update the cache with all bibfiles in use (including bibfiles
347         /// of loaded child documents).
348         void updateBibfilesCache(UpdateScope scope = UpdateMaster) const;
349         ///
350         void invalidateBibinfoCache();
351         /// Return the cache with all bibfiles in use (including bibfiles
352         /// of loaded child documents).
353         support::FileNameList const & 
354                 getBibfilesCache(UpdateScope scope = UpdateMaster) const;
355         /// \return the bibliography information for this buffer's master,
356         /// or just for it, if it isn't a child.
357         BiblioInfo const & masterBibInfo() const;
358         /// \return the bibliography information for this buffer ONLY.
359         BiblioInfo const & localBibInfo() const;
360         ///
361         void getLabelList(std::vector<docstring> &) const;
362
363         ///
364         void changeLanguage(Language const * from, Language const * to);
365
366         ///
367         bool isMultiLingual() const;
368
369         ///
370         BufferParams & params();
371         BufferParams const & params() const;
372
373         /** The list of paragraphs.
374             This is a linked list of paragraph, this list holds the
375             whole contents of the document.
376          */
377         ParagraphList & paragraphs();
378         ParagraphList const & paragraphs() const;
379
380         /// LyX version control object.
381         LyXVC & lyxvc();
382         LyXVC const & lyxvc() const;
383
384         /// Where to put temporary files.
385         std::string const temppath() const;
386
387         /// Used when typesetting to place errorboxes.
388         TexRow const & texrow() const;
389         TexRow & texrow();
390
391         ///
392         ParIterator par_iterator_begin();
393         ///
394         ParConstIterator par_iterator_begin() const;
395         ///
396         ParIterator par_iterator_end();
397         ///
398         ParConstIterator par_iterator_end() const;
399
400         // Position of the child buffer where it appears first in the master.
401         DocIterator firstChildPosition(Buffer const * child);
402
403         /** \returns true only when the file is fully loaded.
404          *  Used to prevent the premature generation of previews
405          *  and by the citation inset.
406          */
407         bool isFullyLoaded() const;
408         /// Set by buffer_funcs' newFile.
409         void setFullyLoaded(bool);
410
411         /// Our main text (inside the top InsetText)
412         Text & text() const;
413
414         /// Our top InsetText
415         Inset & inset() const;
416
417         //
418         // Macro handling
419         //
420         /// Collect macro definitions in paragraphs
421         void updateMacros() const;
422         /// Iterate through the whole buffer and try to resolve macros
423         void updateMacroInstances() const;
424
425         /// List macro names of this buffer, the parent and the children
426         void listMacroNames(MacroNameSet & macros) const;
427         /// Collect macros of the parent and its children in front of this buffer.
428         void listParentMacros(MacroSet & macros, LaTeXFeatures & features) const;
429
430         /// Return macro defined before pos (or in the master buffer)
431         MacroData const * getMacro(docstring const & name, DocIterator const & pos, bool global = true) const;
432         /// Return macro defined anywhere in the buffer (or in the master buffer)
433         MacroData const * getMacro(docstring const & name, bool global = true) const;
434         /// Return macro defined before the inclusion of the child
435         MacroData const * getMacro(docstring const & name, Buffer const & child, bool global = true) const;
436
437         /// Collect user macro names at loading time
438         typedef std::set<docstring> UserMacroSet;
439         UserMacroSet usermacros;
440
441         /// Replace the inset contents for insets which InsetCode is equal
442         /// to the passed \p inset_code.
443         void changeRefsIfUnique(docstring const & from, docstring const & to,
444                 InsetCode code);
445
446         /// get source code (latex/docbook) for some paragraphs, or all paragraphs
447         /// including preamble
448         void getSourceCode(odocstream & os, pit_type par_begin, pit_type par_end,
449                 bool full_source) const;
450
451         /// Access to error list.
452         /// This method is used only for GUI visualisation of Buffer related
453         /// errors (like parsing or LateX compilation). This method is const
454         /// because modifying the returned ErrorList does not touch the document
455         /// contents.
456         ErrorList & errorList(std::string const & type) const;
457
458         /// The Toc backend.
459         /// This is useful only for screen visualisation of the Buffer. This
460         /// method is const because modifying this backend does not touch
461         /// the document contents.
462         TocBackend & tocBackend() const;
463
464         ///
465         Undo & undo();
466
467         /// This function is called when the buffer is changed.
468         void changed() const;
469         ///
470         void updateTocItem(std::string const &, DocIterator const &) const;
471         /// This function is called when the buffer structure is changed.
472         void structureChanged() const;
473         /// This function is called when some parsing error shows up.
474         void errors(std::string const & err, bool from_master = false) const;
475         /// This function is called when the buffer busy status change.
476         void setBusy(bool on) const;
477         /// This function is called when the buffer readonly status change.
478         void setReadOnly(bool on) const;
479         /// Update window titles of all users.
480         void updateTitles() const;
481         /// Reset autosave timers for all users.
482         void resetAutosaveTimers() const;
483         ///
484         void message(docstring const & msg) const;
485
486         ///
487         void setGuiDelegate(frontend::GuiBufferDelegate * gui);
488         ///
489         bool hasGuiDelegate() const;
490
491         ///
492         void autoSave() const;
493         ///
494         void removeAutosaveFile() const;
495         ///
496         void moveAutosaveFile(support::FileName const & old) const;
497         ///
498         support::FileName getAutosaveFilename() const;
499
500         /// return the format of the buffer on a string
501         std::string bufferFormat() const;
502         /// return the default output format of the current backend
503         std::string getDefaultOutputFormat() const;
504
505         ///
506         bool doExport(std::string const & format, bool put_in_tempdir,
507                 std::string & result_file) const;
508         ///
509         bool doExport(std::string const & format, bool put_in_tempdir) const;
510         ///
511         bool preview(std::string const & format) const;
512         ///
513         bool isExportable(std::string const & format) const;
514         ///
515         std::vector<Format const *> exportableFormats(bool only_viewable) const;
516         ///
517         bool isExportableFormat(std::string const & format) const;
518
519         ///
520         typedef std::vector<std::pair<InsetRef *, ParIterator> > References;
521         References & references(docstring const & label);
522         References const & references(docstring const & label) const;
523         void clearReferenceCache() const;
524         void setInsetLabel(docstring const & label, InsetLabel const * il);
525         InsetLabel const * insetLabel(docstring const & label) const;
526
527         /// return a list of all used branches (also in children)
528         void getUsedBranches(std::list<docstring> &, bool const from_master = false) const;
529
530         /// sets the buffer_ member for every inset in this buffer.
531         // FIXME This really shouldn't be needed, but at the moment it's not
532         // clear how to do it just for the individual pieces we need.
533         void setBuffersForInsets() const;
534         /// Updates screen labels and some other information associated with
535         /// insets and paragraphs. Actually, it's more like a general "recurse
536         /// through the Buffer" routine, that visits all the insets and paragraphs.
537         void updateLabels() const { updateLabels(UpdateMaster, false); }
538         /// \param scope: whether to start with the master document or just
539         /// do this one.
540         /// \param output: whether we are preparing for output.
541         void updateLabels(UpdateScope scope, bool output) const;
542         /// 
543         void updateLabels(ParIterator & parit, bool output) const;
544
545         /// Spellcheck starting from \p from.
546         /// \p from initial position, will then points to the next misspelled
547         ///    word.
548         /// \p to will points to the end of the next misspelled word.
549         /// \p word_lang will contain the found misspelled word.
550         /// \return progress if a new word was found.
551         int spellCheck(DocIterator & from, DocIterator & to,
552                 WordLangTuple & word_lang, docstring_list & suggestions) const;
553
554 private:
555         /// search for macro in local (buffer) table or in children
556         MacroData const * getBufferMacro(docstring const & name,
557                                          DocIterator const & pos) const;
558         /** Update macro table starting with position of it
559             \param it in some text inset
560         */
561         void updateMacros(DocIterator & it,
562                                      DocIterator & scope) const;
563         ///
564         void setLabel(ParIterator & it) const;
565         ///
566         void collectRelatives(BufferSet & bufs) const;
567
568         ///
569         bool readFileHelper(support::FileName const & s);
570         ///
571         std::vector<std::string> backends() const;
572         /** Inserts a file into a document
573             \return \c false if method fails.
574         */
575         ReadStatus readFile(Lexer &, support::FileName const & filename,
576                             bool fromString = false);
577
578         /** If we have branches that use the file suffix
579             feature, return the file name with suffix appended.
580         */
581         support::FileName exportFileName() const;
582
583         /// Use the Pimpl idiom to hide the internals.
584         class Impl;
585         /// The pointer never changes although *pimpl_'s contents may.
586         Impl * const d;
587         ///
588         frontend::GuiBufferDelegate * gui_;
589
590         /// This function is called when the buffer structure is changed.
591         Signal structureChanged_;
592         /// This function is called when some parsing error shows up.
593         //Signal errors(std::string const &) = 0;
594         /// This function is called when some message shows up.
595         //Signal message(docstring const &) = 0;
596         /// This function is called when the buffer busy status change.
597         //Signal setBusy(bool) = 0;
598         /// Reset autosave timers for all users.
599         Signal resetAutosaveTimers_;
600 };
601
602
603 } // namespace lyx
604
605 #endif