Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions CHANGES.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
## Version 10.4.0 (work in process)

Deprecations:

- (chore) `requireLanguage` is deprecated.
- Prefer `getLanguage` (with custom error handling) or built-time dependencies.
- See [Library API](https://highlightjs.readthedocs.io/en/latest/api.html#requirelanguage-name) for more information.

Parser:

- fix(vue): Language name now appears in CSS class (#2807) [Michael Rush][]
Expand Down
15 changes: 11 additions & 4 deletions docs/api.rst
Original file line number Diff line number Diff line change
Expand Up @@ -45,8 +45,10 @@ Returns an object with the following properties:
* ``second_best``: object with the same structure for second-best heuristically detected language (may be absent)


``fixMarkup(value)``
--------------------
``fixMarkup(value)`` (deprecated as of 10.3)
--------------------------------------------

**fixMarkup is deprecated and will be removed entirely in v11.**

Post-processing of the highlighted markup. Currently consists of replacing indentation TAB characters and using ``<br>`` tags instead of new-line characters. Options are set globally with ``configure``.

Expand Down Expand Up @@ -138,8 +140,13 @@ Looks up a language by name or alias.
Returns the language object if found, ``undefined`` otherwise.


``requireLanguage(name)``
-------------------------
``requireLanguage(name)`` (deprecated as of 10.4)
-------------------------------------------------

**This has been deprecated and will be removed in a future release.** If you
need this type of functionality use ``getLanguage`` with your own error
handling. It is highly recommended that all inter-dependencies between grammars
be handled at built-time, not run-time. This is what the core library now does.

Looks up a language by name or alias.

Expand Down
16 changes: 15 additions & 1 deletion src/highlight.js
Original file line number Diff line number Diff line change
Expand Up @@ -592,12 +592,23 @@ const HLJS = function(hljs) {

const sorted = results.sort((a, b) => {
// sort base on relevance
return b.relevance - a.relevance;
if (a.relevance !== b.relevance) return b.relevance - a.relevance;

// always award the tie to the base language
// ie if C++ and Arduino are tied, it's more likely to be C++
if (a.language && b.language) {
if (getLanguage(a.language).supersetOf === b.language) {
return 1;
} else if (getLanguage(b.language).supersetOf === a.language) {
return -1;
}
}

// otherwise say they are equal, which has the effect of sorting on
// relevance while preserving the original ordering - which is how ties
// have historically been settled, ie the language that comes first always
// wins in the case of a tie
return 0;
});

const [best, secondBest] = sorted;
Expand Down Expand Up @@ -787,6 +798,9 @@ const HLJS = function(hljs) {
@returns {Language | never}
*/
function requireLanguage(name) {
console.warn("requireLanguage is deprecated and will be removed entirely in the future.");
console.warn("Please see https://github.com/highlightjs/highlight.js/pull/2844");
Comment on lines +801 to +802
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should there be some sort of check here for checking whether highlight.js is running a production environment?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The idea is that everyone can see it. It only shows up in console so it’s not disruptive. And after this PR it’s also immediately actionable so it’s not something that people have to wait till version 11. Someone can see it immediately make changes to that code base to make it go away.

I’m pretty sure this is consistent with the other deprecation notices.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I do certainly wish there were some better way to handle this but like I can’t really think of what it would be too of my head.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't really feel strongly about this either way. My initial thought was someone using a plug-in in their CMS that had a bundled version of highlight.js or something similar and fixing the warning was beyond their control until the plug-in maintainer updated it.

Closest thing I can think of is webpack's support for process.env.node_env === 'production' but I can't say I've ever bothered looking for a browser-only solution other than having *.production.min.js and *.development.js files

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There is minified or not (perhaps could have a flag based on the build type) but there is no guarantee one is using minified in production and un-minified for development work. Unless you're hacking on the library you're probably just using the minified version everywhere.


const lang = getLanguage(name);
if (lang) { return lang; }

Expand Down
177 changes: 89 additions & 88 deletions src/languages/arduino.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,109 +2,110 @@
Language: Arduino
Author: Stefania Mellai <[email protected]>
Description: The Arduino® Language is a superset of C++. This rules are designed to highlight the Arduino® source code. For info about language see http://www.arduino.cc.
Requires: cpp.js
Website: https://www.arduino.cc
*/

import cPlusPlus from './cpp.js';

/** @type LanguageFn */
export default function(hljs) {

var ARDUINO_KW = {
keyword:
'boolean byte word String',
built_in:
'setup loop ' +
'KeyboardController MouseController SoftwareSerial ' +
'EthernetServer EthernetClient LiquidCrystal ' +
'RobotControl GSMVoiceCall EthernetUDP EsploraTFT ' +
'HttpClient RobotMotor WiFiClient GSMScanner ' +
'FileSystem Scheduler GSMServer YunClient YunServer ' +
'IPAddress GSMClient GSMModem Keyboard Ethernet ' +
'Console GSMBand Esplora Stepper Process ' +
'WiFiUDP GSM_SMS Mailbox USBHost Firmata PImage ' +
'Client Server GSMPIN FileIO Bridge Serial ' +
'EEPROM Stream Mouse Audio Servo File Task ' +
'GPRS WiFi Wire TFT GSM SPI SD ' +
'runShellCommandAsynchronously analogWriteResolution ' +
'retrieveCallingNumber printFirmwareVersion ' +
'analogReadResolution sendDigitalPortPair ' +
'noListenOnLocalhost readJoystickButton setFirmwareVersion ' +
'readJoystickSwitch scrollDisplayRight getVoiceCallStatus ' +
'scrollDisplayLeft writeMicroseconds delayMicroseconds ' +
'beginTransmission getSignalStrength runAsynchronously ' +
'getAsynchronously listenOnLocalhost getCurrentCarrier ' +
'readAccelerometer messageAvailable sendDigitalPorts ' +
'lineFollowConfig countryNameWrite runShellCommand ' +
'readStringUntil rewindDirectory readTemperature ' +
'setClockDivider readLightSensor endTransmission ' +
'analogReference detachInterrupt countryNameRead ' +
'attachInterrupt encryptionType readBytesUntil ' +
'robotNameWrite readMicrophone robotNameRead cityNameWrite ' +
'userNameWrite readJoystickY readJoystickX mouseReleased ' +
'openNextFile scanNetworks noInterrupts digitalWrite ' +
'beginSpeaker mousePressed isActionDone mouseDragged ' +
'displayLogos noAutoscroll addParameter remoteNumber ' +
'getModifiers keyboardRead userNameRead waitContinue ' +
'processInput parseCommand printVersion readNetworks ' +
'writeMessage blinkVersion cityNameRead readMessage ' +
'setDataMode parsePacket isListening setBitOrder ' +
'beginPacket isDirectory motorsWrite drawCompass ' +
'digitalRead clearScreen serialEvent rightToLeft ' +
'setTextSize leftToRight requestFrom keyReleased ' +
'compassRead analogWrite interrupts WiFiServer ' +
'disconnect playMelody parseFloat autoscroll ' +
'getPINUsed setPINUsed setTimeout sendAnalog ' +
'readSlider analogRead beginWrite createChar ' +
'motorsStop keyPressed tempoWrite readButton ' +
'subnetMask debugPrint macAddress writeGreen ' +
'randomSeed attachGPRS readString sendString ' +
'remotePort releaseAll mouseMoved background ' +
'getXChange getYChange answerCall getResult ' +
'voiceCall endPacket constrain getSocket writeJSON ' +
'getButton available connected findUntil readBytes ' +
'exitValue readGreen writeBlue startLoop IPAddress ' +
'isPressed sendSysex pauseMode gatewayIP setCursor ' +
'getOemKey tuneWrite noDisplay loadImage switchPIN ' +
'onRequest onReceive changePIN playFile noBuffer ' +
'parseInt overflow checkPIN knobRead beginTFT ' +
'bitClear updateIR bitWrite position writeRGB ' +
'highByte writeRed setSpeed readBlue noStroke ' +
'remoteIP transfer shutdown hangCall beginSMS ' +
'endWrite attached maintain noCursor checkReg ' +
'checkPUK shiftOut isValid shiftIn pulseIn ' +
'connect println localIP pinMode getIMEI ' +
'display noBlink process getBand running beginSD ' +
'drawBMP lowByte setBand release bitRead prepare ' +
'pointTo readRed setMode noFill remove listen ' +
'stroke detach attach noTone exists buffer ' +
'height bitSet circle config cursor random ' +
'IRread setDNS endSMS getKey micros ' +
'millis begin print write ready flush width ' +
'isPIN blink clear press mkdir rmdir close ' +
'point yield image BSSID click delay ' +
'read text move peek beep rect line open ' +
'seek fill size turn stop home find ' +
'step tone sqrt RSSI SSID ' +
'end bit tan cos sin pow map abs max ' +
'min get run put',
literal:
'DIGITAL_MESSAGE FIRMATA_STRING ANALOG_MESSAGE ' +
'REPORT_DIGITAL REPORT_ANALOG INPUT_PULLUP ' +
'SET_PIN_MODE INTERNAL2V56 SYSTEM_RESET LED_BUILTIN ' +
'INTERNAL1V1 SYSEX_START INTERNAL EXTERNAL ' +
'DEFAULT OUTPUT INPUT HIGH LOW'
const ARDUINO_KW = {
keyword:
'boolean byte word String',
built_in:
'setup loop ' +
'KeyboardController MouseController SoftwareSerial ' +
'EthernetServer EthernetClient LiquidCrystal ' +
'RobotControl GSMVoiceCall EthernetUDP EsploraTFT ' +
'HttpClient RobotMotor WiFiClient GSMScanner ' +
'FileSystem Scheduler GSMServer YunClient YunServer ' +
'IPAddress GSMClient GSMModem Keyboard Ethernet ' +
'Console GSMBand Esplora Stepper Process ' +
'WiFiUDP GSM_SMS Mailbox USBHost Firmata PImage ' +
'Client Server GSMPIN FileIO Bridge Serial ' +
'EEPROM Stream Mouse Audio Servo File Task ' +
'GPRS WiFi Wire TFT GSM SPI SD ' +
'runShellCommandAsynchronously analogWriteResolution ' +
'retrieveCallingNumber printFirmwareVersion ' +
'analogReadResolution sendDigitalPortPair ' +
'noListenOnLocalhost readJoystickButton setFirmwareVersion ' +
'readJoystickSwitch scrollDisplayRight getVoiceCallStatus ' +
'scrollDisplayLeft writeMicroseconds delayMicroseconds ' +
'beginTransmission getSignalStrength runAsynchronously ' +
'getAsynchronously listenOnLocalhost getCurrentCarrier ' +
'readAccelerometer messageAvailable sendDigitalPorts ' +
'lineFollowConfig countryNameWrite runShellCommand ' +
'readStringUntil rewindDirectory readTemperature ' +
'setClockDivider readLightSensor endTransmission ' +
'analogReference detachInterrupt countryNameRead ' +
'attachInterrupt encryptionType readBytesUntil ' +
'robotNameWrite readMicrophone robotNameRead cityNameWrite ' +
'userNameWrite readJoystickY readJoystickX mouseReleased ' +
'openNextFile scanNetworks noInterrupts digitalWrite ' +
'beginSpeaker mousePressed isActionDone mouseDragged ' +
'displayLogos noAutoscroll addParameter remoteNumber ' +
'getModifiers keyboardRead userNameRead waitContinue ' +
'processInput parseCommand printVersion readNetworks ' +
'writeMessage blinkVersion cityNameRead readMessage ' +
'setDataMode parsePacket isListening setBitOrder ' +
'beginPacket isDirectory motorsWrite drawCompass ' +
'digitalRead clearScreen serialEvent rightToLeft ' +
'setTextSize leftToRight requestFrom keyReleased ' +
'compassRead analogWrite interrupts WiFiServer ' +
'disconnect playMelody parseFloat autoscroll ' +
'getPINUsed setPINUsed setTimeout sendAnalog ' +
'readSlider analogRead beginWrite createChar ' +
'motorsStop keyPressed tempoWrite readButton ' +
'subnetMask debugPrint macAddress writeGreen ' +
'randomSeed attachGPRS readString sendString ' +
'remotePort releaseAll mouseMoved background ' +
'getXChange getYChange answerCall getResult ' +
'voiceCall endPacket constrain getSocket writeJSON ' +
'getButton available connected findUntil readBytes ' +
'exitValue readGreen writeBlue startLoop IPAddress ' +
'isPressed sendSysex pauseMode gatewayIP setCursor ' +
'getOemKey tuneWrite noDisplay loadImage switchPIN ' +
'onRequest onReceive changePIN playFile noBuffer ' +
'parseInt overflow checkPIN knobRead beginTFT ' +
'bitClear updateIR bitWrite position writeRGB ' +
'highByte writeRed setSpeed readBlue noStroke ' +
'remoteIP transfer shutdown hangCall beginSMS ' +
'endWrite attached maintain noCursor checkReg ' +
'checkPUK shiftOut isValid shiftIn pulseIn ' +
'connect println localIP pinMode getIMEI ' +
'display noBlink process getBand running beginSD ' +
'drawBMP lowByte setBand release bitRead prepare ' +
'pointTo readRed setMode noFill remove listen ' +
'stroke detach attach noTone exists buffer ' +
'height bitSet circle config cursor random ' +
'IRread setDNS endSMS getKey micros ' +
'millis begin print write ready flush width ' +
'isPIN blink clear press mkdir rmdir close ' +
'point yield image BSSID click delay ' +
'read text move peek beep rect line open ' +
'seek fill size turn stop home find ' +
'step tone sqrt RSSI SSID ' +
'end bit tan cos sin pow map abs max ' +
'min get run put',
literal:
'DIGITAL_MESSAGE FIRMATA_STRING ANALOG_MESSAGE ' +
'REPORT_DIGITAL REPORT_ANALOG INPUT_PULLUP ' +
'SET_PIN_MODE INTERNAL2V56 SYSTEM_RESET LED_BUILTIN ' +
'INTERNAL1V1 SYSEX_START INTERNAL EXTERNAL ' +
'DEFAULT OUTPUT INPUT HIGH LOW'
};

var ARDUINO = hljs.requireLanguage('cpp').rawDefinition();
const ARDUINO = cPlusPlus(hljs);

var kws = ARDUINO.keywords;
const kws = /** @type {Record<string,any>} */ (ARDUINO.keywords);

kws.keyword += ' ' + ARDUINO_KW.keyword;
kws.literal += ' ' + ARDUINO_KW.literal;
kws.built_in += ' ' + ARDUINO_KW.built_in;

ARDUINO.name = 'Arduino';
ARDUINO.aliases = ['ino'];
ARDUINO.supersetOf = "cpp";

return ARDUINO;
}
5 changes: 3 additions & 2 deletions src/languages/c.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,13 @@
Language: C
Category: common, system
Website: https://en.wikipedia.org/wiki/C_(programming_language)
Requires: c-like.js
*/

import cLike from './c-like.js';

/** @type LanguageFn */
export default function(hljs) {
var lang = hljs.requireLanguage('c-like').rawDefinition();
const lang = cLike(hljs);
// Until C is actually different than C++ there is no reason to auto-detect C
// as it's own language since it would just fail auto-detect testing or
// simply match with C++.
Expand Down
5 changes: 3 additions & 2 deletions src/languages/cpp.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,13 @@
Language: C++
Category: common, system
Website: https://isocpp.org
Requires: c-like.js
*/

import cLike from './c-like.js';

/** @type LanguageFn */
export default function(hljs) {
var lang = hljs.requireLanguage('c-like').rawDefinition();
const lang = cLike(hljs);
// return auto-detection back on
lang.disableAutodetect = false;
lang.name = 'C++';
Expand Down