User:Nardog/RefRenamer

Source: Wikipedia, the free encyclopedia.
RefRenamer
ES2019+ needed)
Source

This is a script for replacing the name attributes of <ref> tags with something descriptive like "Smith-2015". It was developed with focus on names like ":0", ":1" and so on, which are generated by VisualEditor, so by default it only renames them, but you can rename other names found in the source as well.

Installing it adds the link "RefRenamer" to the Tools section of the sidebar on pages related to existing wikipages, which opens a dialog. If it's opened while editing, the source in the edit box will be parsed (slower); otherwise the latest version of the page will be analyzed.

Installation

Add the following to your common.js:

mw.loader.load('//en.wikipedia.org/w/index.php?title=User:Nardog/RefRenamer.js&action=raw&ctype=text/javascript');

Or you may enable the script installer in Preferences → Gadgets and click "Install" in the infobox on this page.

Usage

When the dialog is opened, only references with autogenerated names (":0", "auto1", etc.) are eligible for being renamed. Other named references are listed in the other tab, and you can make them eligible by clicking "+" or "Add all".

The script relies on two main sources for generating new names. One is COinS metadata, which is output by CS1/CS2 templates ({{cite web}}, {{citation}}, etc.). The other is "First phrase", which takes whatever the first characters before any punctuation in the reference text are. The extraction of years works in a similar way. If a date is available in COinS, the greatest integer in it is treated as the year. In case it's not, you may opt in to use any first-occurring four-digit number in the reference text. To avoid collisions, autogenerated names are compared against each other and against the existing ref names within the source. If a name is already taken, a number is appended. You can then manually edit the generated ref names in the table. Clicking Continue opens the editing page with the modified source and diff preloaded.

Options

Main fallback stack
Here you can choose which properties to look for and reorder the priority by dragging the items. If no properties specified here are available in a reference, the textbox in the table will be left blank (which means the name will not be replaced unless input manually).
Properties correspond to COinS as follows (see Module:Citation/CS1/COinS for the logic):
  • Last name: rft.aulast
  • First name: rft.aufirst
  • Author: rft.au
  • Periodical/website: rft.jtitle
  • Publisher: rft.pub, rft.inst
  • Article: rft.atitle, rft.title
  • Book: rft.btitle
  • Domain: Extracted from rft_id
If no COinS metadata is available, "Domain" is taken from the first link in the reference. "First phrase" takes whatever the first characters before any punctuation in the reference text are.
Lowercase
Remove diacritics
Remove punctuation
Replace space with
These affect the main string found through the fallback stack. You can remove spaces by leaving the "Replace space with" textbox blank.
Year
If this is checked, the greatest integer in COinS rft.date will be appended to the string.
Fall back on any 4-digit number
If this is checked and a COinS date is not availabe, any first-occurring four-digit number in the reference text will be appended to the string.
Convert to ASCII
If the year uses language-specific numerals (e.g. "۲۰۱۵"), convert it to ASCII Western Arabic numerals ("2015"). Shown only if a non-ASCII year has been found.
Append Latin letters on collision
If a year is found and the name is already used, append a lowercase Latin letter (e.g. "Jones-2023a") instead of a number. Regardless of the choice in "Collision resolution", the first item will have "a".
Collision resolution
What to do in case a name is already used.
Delimiter
String to be inserted before a year or increment. May be empty.
Insert delimiters only after numerals
If this is checked, the delimiters will be inserted only if the preceding character is a numeral (e.g. "Lee2015" instead of "Lee-2015").
Remove unreused names
If the reference is used only once (i.e. no <ref name="..." />), remove the  name="..." part entirely rather than replace the name.
Apply
Regenerates the new names using the above options. Any changes made in the table will be discarded.
Reset
Restores the script's default options. Does not regenerate new names yet.

Tables

Name
Original name of the reference. The references are sorted by this.
Reference
Output text of the reference.
New name
Here you can see and change the new name generated based on the options above. Leave it empty to keep the original name. Hitting Enter here has the same effect as clicking the Continue button.
Reapply current options
Discards any changes made in the textbox and regenerates a new name using the current options (even if they have been changed since "Apply" was last clicked)—except "Remove unreused names" so it won't uncheck the checkbox.
View/insert properties
List of properties RefRenamer found in COinS metadata or reference text. Clicking on an item inserts the value into the textbox. Property keys are shown alongside the values for reference.
Uncheck to remove
If a checkbox appears inside the textbox, it means the reference is used only once (i.e. no <ref name="..." />). Uncheck it to remove the  name="..." part entirely rather than replace the name.
Remove from references to rename
Moves the reference from "References to rename" to "Other named references".
Add to references to rename
Moves the reference from "Other named references" to "References to rename" and generates a new name based on the current options (even if they have been changed since "Apply" was last clicked).

Other

Add all
Adds all references in "Other named references" to "References to rename" and generates new names based on the current options (even if they have been changed since "Apply" was last clicked).
Reset selection
Adds all references with autogenerated names to "References to rename", and all others to "Other named references".
Continue
Opens the editing page with the modified source and diff preloaded. Saves the options to your browser's local storage so they will be loaded the next time you open the dialog. Gives you an error instead if there are invalid or duplicate names or if no names have been modified.

Limitations

  • Ref names inside templates like {{r}} and {{refn}} are not detected and will not be replaced. The script may warn you if it detects such a template is likely using one of the ref names that may be renamed, but the detection is not perfect so always check the result before/after saving.
  • If two references have names that differ only in the number of underscores or in space vs. underscore, as in a b and a_b (which is technically allowed), both references are ignored because the script can't match up the names and the references.

Caveats

While the script has checks in place for invalid or duplicate names, there might be unforeseen cases where it removes or replaces something it shouldn't. Please use it at your own risk (as you must any script) and make sure the result is correct before/after saving.

Excessive use of this script may be considered

WP:COSMETICBOT
.

Advanced name generation

You may generate ref names in more complex ways than the script's GUI allows, by adding a callback to the MediaWiki front-end hook refrenamer.rename in your common.js. For example, this code renames references with an author last name, a year, and a page number to "Chen 2017 p. 1", "Chen 2017 pp. 2-3", etc., depending on the value of the page number.

mw.hook('refrenamer.rename').add(function (ref) {
	if (ref.props.aulast && ref.props.year && ref.props.pages) {
		var separator = /[-,]/.test(ref.props.pages) ? ' pp. ' : ' p. ';
		ref.newName = ref.props.aulast + ' ' + ref.props.year + separator + ref.props.pages;
	}
});

ref is an object containing information about each reference. It comes with two properties and one method:

  • name – original reference name
  • props – an object consisting of key–value pairs of properties obtained from COinS metadata and reference text
  • getElement() – returns an HTML element for the reference text

If a string is added to the ref object as property newName after the callback runs, RefRenamer will use the string as the new name for the reference. The automatic collision resolution will still take place.

Click View/insert properties under "New name" for what properties are available.

Localization

You may create a translated version of this script with the following code. Note though that the script is built on the assumption that COinS metadata is usually available, which may not be the case on your wiki, and that your wiki may have other needs or conventions in ref names the script does not support.

window.refrenamerMessages = {
	portlet: 'RefRenamer',
	loading: 'Loading RefRenamer...',
	loadingSource: 'Loading the source...',
	loadingHtml: 'Loading HTML...',
	parsing: 'Parsing wikitext...',
	opening: 'Opening the diff...',
	continue: 'Continue',
	main: 'Main fallback stack:',
	lastName: 'Last name',
	firstName: 'First name',
	author: 'Author',
	periodical: 'Periodical/website',
	publisher: 'Publisher',
	article: 'Article',
	book: 'Book',
	domain: 'Domain',
	firstPhrase: 'First phrase',
	lowercase: 'Lowercase',
	removeDia: 'Remove diacritics',
	removePunct: 'Remove punctuation',
	replaceSpace: 'Replace space with:',
	year: 'Year',
	yearFallback: 'Fall back on any 4-digit number',
	yearConvert: 'Convert to ASCII',
	latinIncrement: 'Append Latin letters on collision',
	increment: 'Collision resolution:',
	incrementExample: 'Example',
	incrementExamples: '$1, $2...',
	delimiter: 'Delimiter:',
	delimitConditional: 'Insert delimiters only after numerals',
	removeUnreused: 'Remove unreused names',
	apply: 'Apply',
	reset: 'Reset',
	tableName: 'Name',
	tableCaption: 'References to rename',
	tableRef: 'Reference',
	tableNewName: 'New name',
	tableAddRemove: '±',
	reapplyTooltip: 'Reapply current options',
	propsTooltip: 'View/insert properties',
	keepTooltip: 'Uncheck to remove',
	tableRemove: '(Remove)',
	removeTooltip: 'Remove from references to rename',
	otherTableCaption: 'Other named references',
	notReused: '(not reused)',
	expand: 'Expand',
	collapse: 'Collapse',
	addTooltip: 'Add to references to rename',
	addAll: 'Add all',
	resetSelection: 'Reset selection',
	noNamesAlert: 'The source does not contain ref names to rename.',
	noChangesError: 'No names have been modified.',
	numericError: 'The following names are invalid as they consist only of numerals:',
	duplicatesError: 'The following names are already used or input more than once:',
	templatesWarn: 'Ref names in the following templates will not be replaced:',
	invalidWarn: 'The following names have been ignored because it could not be determined which references correspond to them:',
	summary: 'Replaced [[$1|VE ref names]] using [[$2|RefRenamer]]',
	genericSummary: 'Renamed references using [[$1|RefRenamer]]'
};

mw.loader.load('//en.wikipedia.org/w/index.php?title=User:Nardog/RefRenamer.js&action=raw&ctype=text/javascript');