Example #1
0
        bool ReadDatabaseFromFile(string filename)
        {
            if (string.IsNullOrEmpty(filename))
            {
                return(false);
            }

            var fileInfo = new FileInfo(filename);

            // If we are looking at the same file and it hasn't been updated then just reuse it
            if (lastLoadedDatabase != null && fileInfo.FullName == lastLoadedDatabase.Filename && fileInfo.LastWriteTime == lastLoadedDatabase.Timestamp)
            {
                Debug.Assert(lastLoadedDatabase != null);
                return(true);
            }

            try
            {
                lastLoadedDatabase = BibTexHelper.LoadBibTexDatabase(filename);

                return(lastLoadedDatabase != null);
            }
            catch
            {}

            return(false);
        }
Example #2
0
		public void LoadSpecialCharactersDatabase()
		{
			var data = File.ReadAllText(@"Sample Files\b4w.bib", Encoding.GetEncoding(1252));
			var parser = new BibTexParser(new BibTexLexer(data));

			specialCharactersDatabase = parser.Parse();
		}
Example #3
0
        public BibTexDatabase GetDatabaseTest()
        {
            string         documentDatabaseFilename = "E:\\D4W_Test\\XML.bib";
            BibTexDatabase result = BibTexHelper.LoadBibTexDatabase(documentDatabaseFilename);

            return(result);
        }
Example #4
0
        public void LoadSpecialCharactersDatabase()
        {
            var data   = File.ReadAllText(@"Sample Files\b4w.bib", Encoding.GetEncoding(1252));
            var parser = new BibTexParser(new BibTexLexer(data));

            specialCharactersDatabase = parser.Parse();
        }
Example #5
0
		void ParseRootEntry(BibTexDatabase database)
		{
			Consume(TokenType.At);

			var entryType = Consume(TokenType.Text).Data;

			Consume(TokenType.OpeningBrace);

			switch (entryType.ToLower())
			{
				case "string":
					ParseAbbreviation(database);
					break;

				case "preamble":
					ParsePreamble();
					break;

				case "comment":
					ParseComment();
					break;

				default:
					var entry = ParseEntry(database, entryType);
					database.AddEntry(entry);
					//Console.WriteLine("@{0}{{{1},", entry.EntryType, entry.Name);
					break;

			}
		}
Example #6
0
            int UpdateCitationsFromDatabase(BibTexDatabase database)
            {
                if (database == null || !Settings.Instance.RefreshUpdatesCitationsFromDatabase)
                {
                    return(-1);
                }

                var changesMade = 0;

                foreach (var cslField in documentController.EnumerateCSLFields())
                {
                    if (!IsCitationField(cslField))
                    {
                        continue;
                    }

                    var existingCitation = GetCitation(cslField.Code.Text);

                    var sources = Helper.ExtractSources(existingCitation, database);

                    // We can't risk losing a whole citation cluster because one item is not in the database
                    // so we skip the compare and keep the inline version
                    if (sources.Count != existingCitation.CitationItems.Length)
                    {
                        continue;
                    }

                    // We also won't update a cluster containing unknown items
                    // since this behaviour is undefined
                    if (ContainsUnknownItems(sources))
                    {
                        continue;
                    }

                    var databaseCitation = documentController.CreateInlineCitation(sources, existingCitation.CitationID);
                    Debug.Assert(existingCitation.JSObject != databaseCitation.JSObject);

                    if (DatabaseVersionIsDifferent(existingCitation, databaseCitation))
                    {
                        // Change the Field Code Text
                        cslField.Code.Text = CreateFieldCodeText(databaseCitation);
                        FormatCitationField(cslField);

                        // Increment the changed counter
                        changesMade++;
                    }
                }

                return(changesMade);
            }
Example #7
0
        public BibTexDatabase Parse()
        {
            var database = new BibTexDatabase();

            Consume();

            while (true)
            {
                switch (Current.TokenType)
                {
                    case TokenType.EOF:
                        return database;

                    case TokenType.At:
                        ParseRootEntry(database);
                        break;

                    default:
                        Consume();
                        break;
                }
            }
        }
Example #8
0
        void ParseAbbreviation(BibTexDatabase database)
        {
            var entryName = Consume(TokenType.Text).Data;

            Consume(TokenType.Equals);

            var entryValue = Consume().Data;

            // Consume any trailing comma
            if (Current.TokenType == TokenType.Comma) Consume();

            Consume(TokenType.ClosingBrace);

            //Console.WriteLine("@string{{{0} = \"{1}\"}}", entryName, entryValue);
            database.AddAbbreviation(entryName, entryValue);
        }
Example #9
0
        void ParseTag(BibTexDatabase database, Entry entry, string tagName)
        {
            Consume(TokenType.Equals);

            string value = null;

            while(true)
            {
                switch (Current.TokenType)
                {
                    case TokenType.QuotedString:
                        value += Consume().Data;
                        break;

                    case TokenType.BracedString:
                        value += Consume().Data;
                        break;

                    case TokenType.Text:
                        var token = Consume().Data;
                        value += database.GetAbbreviation(token, token);

                        break;

                    case TokenType.Hash:
                        break;

                    default:
                        throw new NotImplementedException();
                }

                if (Current.TokenType != TokenType.Hash) break;
                Consume();
            }

            entry.AddTag(new TagEntry(tagName, value));
        }
Example #10
0
        Entry ParseEntry(BibTexDatabase database, string entryType)
        {
            var entryName = Consume(TokenType.Text).Data;
            var entry = new Entry(entryType, entryName, Helper.GetClassificationForType(entryType));

            while(true)
            {
                var token = Consume();

                switch (token.TokenType)
                {
                    case TokenType.EOF:
                        return entry;

                    case TokenType.ClosingBrace:
                        return entry;

                    case TokenType.Equals:
                        break;

                    case TokenType.Comma:
                        break;

                    case TokenType.Text:
                        ParseTag(database, entry, token.Data);
                        break;

                    case TokenType.OpeningBrace:
                        break;

                    default:
                        throw new TemplateParseException("Unexpected token: " + token.TokenType.ToString() , currentToken.Line, currentToken.Column);
                }
            }
        }
        public void Reset(BibTexDatabase database)
        {
            if (database == null)
            {
                database = new BibTexDatabase();
            }

            this.database = database;

            allEntries = new List <SelectableReference>(database.EntryCount);

            var yearList = new List <string>();

            foreach (var entry in database.Entries)
            {
                var selectableReference = new SelectableReference
                {
                    Selected  = false,
                    ID        = entry.Name,
                    Title     = entry["title", TagEntry.Empty].Display,
                    Authors   = entry["author", TagEntry.Empty].Display,
                    Year      = entry["year", TagEntry.Empty].Display,
                    Timestamp = entry["timestamp", TagEntry.Empty].Display,
                    Pages     = string.Empty
                };

                allEntries.Add(selectableReference);

                if (selectableReference.Year.Length == 4 && !yearList.Contains(selectableReference.Year))
                {
                    yearList.Add(selectableReference.Year);
                }
            }

            source = new BindingListAce <SelectableReference>(allEntries)
            {
                AllowNew    = false,
                AllowRemove = false
            };


            bsSelectableReferences.DataSource = source;

            grid.AutoResizeColumns();

            bsSelectableReferences.ListChanged +=
                (sender, args) =>
            {
                Debug.WriteLine("bsSelectableReferences.ListChanged.ListChanged " + args.ListChangedType);
                UpdateAddButton();
            };

            yearList.Sort();
            yearList.Insert(0, "(any)");
            cmbYear.Items.AddRange(yearList.ToArray());
            cmbYear.SelectedIndex = 0;

            UpdateFilter();

            btnChooseDatabase.Visible = Settings.Instance.AllowPerDocumentDatabases;
        }
Example #12
0
        public static List <EntryAndPagePair> ExtractSources(JSInlineCitation inlineCitation, BibTexDatabase currentDatabase)
        {
            var result = new List <EntryAndPagePair>(inlineCitation.CitationItems.Length);

            for (var i = 0; i < inlineCitation.CitationItems.Length; i++)
            {
                var id = inlineCitation.CitationItems[i].ID;
                if (string.IsNullOrEmpty(id))
                {
                    continue;
                }

                // This shouldn't be needed but the pre-release version included
                // the '#<Page>' suffix here as well as in the item ID
                // We remove it here; use the Locator and the document
                // will correct itself on the next Refresh
                var hashIndex = id.IndexOf('#');
                if (hashIndex != -1)
                {
                    id = id.Substring(0, hashIndex);
                }

                var entry = currentDatabase[id];

                // If an entry cannot be found, we skip it
                if (entry == null)
                {
                    continue;
                }

                var authorProcessorControl = GetAuthorProcessorControl(inlineCitation.CitationItems[i]);

                result.Add(new EntryAndPagePair(entry, inlineCitation.CitationItems[i].Locator)
                {
                    AuthorProcessorControl = authorProcessorControl
                });
            }

            return(result);
        }
		public void Reset(BibTexDatabase database)
		{
			if (database == null)
			{
				database = new BibTexDatabase();
			}

			this.database = database;

			allEntries = new List<SelectableReference>(database.EntryCount);

			var yearList = new List<string>();

			foreach(var entry in database.Entries)
			{
				var selectableReference = new SelectableReference
				                         	{
				                         		Selected = false,
												ID = entry.Name,
				                         		Title = entry["title", TagEntry.Empty].Display,
				                         		Authors = entry["author", TagEntry.Empty].Display,
				                         		Year = entry["year", TagEntry.Empty].Display,
				                         		Timestamp = entry["timestamp", TagEntry.Empty].Display,
												Pages = string.Empty
				                         	};

				allEntries.Add(selectableReference);

				if (selectableReference.Year.Length == 4 && !yearList.Contains(selectableReference.Year))
				{
					yearList.Add(selectableReference.Year);
				}
			}

			source = new BindingListAce<SelectableReference>(allEntries)
			             	{
			             		AllowNew = false,
			             		AllowRemove = false
			             	};


			bsSelectableReferences.DataSource = source;

			grid.AutoResizeColumns();

			bsSelectableReferences.ListChanged +=
				(sender, args) =>
					{
						Debug.WriteLine("bsSelectableReferences.ListChanged.ListChanged " + args.ListChangedType);
						UpdateAddButton();
					};

			yearList.Sort();
			yearList.Insert(0, "(any)");
			cmbYear.Items.AddRange(yearList.ToArray());
			cmbYear.SelectedIndex = 0;

			UpdateFilter();

			btnChooseDatabase.Visible = Settings.Instance.AllowPerDocumentDatabases;
		}
Example #14
0
        public void DoAddReference()
        {
            if (!CurrentDocumentControllerIsReady)
            {
                return;
            }

            if (addinModule.IsEditReference())
            {
                DoEditReference();
                return;
            }

            BibTexDatabase currentDatabase = currentDocumentController.GetDatabase();

            if (currentDatabase == null)
            {
                ShowNoDatabaseMessage();
                return;
            }


            var addReferencesForm = new AddReferencesForm();

            addReferencesForm.Reset(currentDatabase);

            var result = addReferencesForm.ShowDialog();

            if (result == DialogResult.Cancel)
            {
                addReferencesForm.Dispose();
                return;
            }

            // Keep a note of these as early as possible after closing dialog
            var isSequence     = (Control.ModifierKeys & Keys.Control) != 0;
            var isLineSequence = isSequence && (Control.ModifierKeys & Keys.Shift) != 0;

            var entryAndPagePairs = addReferencesForm.GetSelectedReferences();

            if (entryAndPagePairs.Count == 0)
            {
                return;
            }


            // Did the user change the database?
            if (addReferencesForm.Database != currentDatabase)
            {
                try
                {
                    // Yes, so store it with the document
                    currentDocumentController.SetDocumentDatabaseFilename(addReferencesForm.Database.Filename);
                }
                catch
                {}
            }

            addReferencesForm.Dispose();

            currentDocumentController.DoInsertCitation(entryAndPagePairs, isSequence, isLineSequence);
        }
Example #15
0
		public static List<EntryAndPagePair> ExtractSources(JSInlineCitation inlineCitation, BibTexDatabase currentDatabase)
		{
			var result = new List<EntryAndPagePair>(inlineCitation.CitationItems.Length);

			for(var i = 0; i < inlineCitation.CitationItems.Length; i++)
			{
				var id = inlineCitation.CitationItems[i].ID;
				if (string.IsNullOrEmpty(id)) continue;

				// This shouldn't be needed but the pre-release version included
				// the '#<Page>' suffix here as well as in the item ID
				// We remove it here; use the Locator and the document
				// will correct itself on the next Refresh
				var hashIndex = id.IndexOf('#');
				if (hashIndex != -1)
				{
					id = id.Substring(0, hashIndex);
				}

				var entry = currentDatabase[id];

				// If an entry cannot be found, we skip it
				if (entry == null) continue;

				var authorProcessorControl = GetAuthorProcessorControl(inlineCitation.CitationItems[i]);

				result.Add(new EntryAndPagePair(entry, inlineCitation.CitationItems[i].Locator)
				           {
					           AuthorProcessorControl = authorProcessorControl
				           });
			}

			return result;
		}
Example #16
0
		bool ReadDatabaseFromFile(string filename)
		{
			if (string.IsNullOrEmpty(filename)) return false;

			var fileInfo = new FileInfo(filename);

			// If we are looking at the same file and it hasn't been updated then just reuse it
			if (lastLoadedDatabase != null && fileInfo.FullName == lastLoadedDatabase.Filename && fileInfo.LastWriteTime == lastLoadedDatabase.Timestamp)
			{
				Debug.Assert(lastLoadedDatabase != null);
				return true;
			}

			try
			{
				lastLoadedDatabase = BibTexHelper.LoadBibTexDatabase(filename);

				return lastLoadedDatabase != null;
			}
			catch
			{}

			return false;
		}
Example #17
0
		void ParseTag(BibTexDatabase database, Entry entry, string tagName)
		{
			Consume(TokenType.Equals);

			string value = null;
            Token LastToken;
			while(true)
			{
                LastToken = Current;

				switch (Current.TokenType)
				{
					case TokenType.QuotedString:
						value += Consume().Data;
						break;

					case TokenType.BracedString:
						value += Consume().Data;
						break;

					case TokenType.Text:
						var token = Consume().Data;
						value += database.GetAbbreviation(token, token);

						break;

					case TokenType.Hash:
						break;

					default:
						throw new NotImplementedException();
				}
                // [Allen] Check the invalid token like:
                // *************************
                // owner = {Norman}   # LastToken.TokenType == TokenType.BracedString
                // timestamp = {2012-07-19} # Current.TokenType == TokenType.Text
                // *************************
                if (LastToken.TokenType == TokenType.BracedString &&
                    Current.TokenType == TokenType.Text )
                {
                    throw new TemplateParseException("Unexpected token: " + LastToken.TokenType + ". Was expecting: '" + LastToken.Data + ",'", LastToken.Line, LastToken.Column);
                }

				if (Current.TokenType != TokenType.Hash) break;

				Consume();
			} 

			entry.AddTag(new TagEntry(tagName, value));
		}
			int UpdateCitationsFromDatabase(BibTexDatabase database)
			{
				if (database == null || !Settings.Instance.RefreshUpdatesCitationsFromDatabase) return -1;

				var changesMade = 0;

				foreach (var cslField in documentController.EnumerateCSLFields())
				{
					if (!IsCitationField(cslField)) continue;

					var existingCitation = GetCitation(cslField.Code.Text);

					var sources = Helper.ExtractSources(existingCitation, database);

					// We can't risk losing a whole citation cluster because one item is not in the database
					// so we skip the compare and keep the inline version
					if (sources.Count != existingCitation.CitationItems.Length) continue;

					// We also won't update a cluster containing unknown items
					// since this behaviour is undefined
					if (ContainsUnknownItems(sources)) continue;

					var databaseCitation = documentController.CreateInlineCitation(sources, existingCitation.CitationID);
					Debug.Assert(existingCitation.JSObject != databaseCitation.JSObject);

					if (DatabaseVersionIsDifferent(existingCitation, databaseCitation))
					{
						// Change the Field Code Text
						cslField.Code.Text = CreateFieldCodeText(databaseCitation);
						FormatCitationField(cslField);

						// Increment the changed counter
						changesMade++;
					}
				}

				return changesMade;
			}