Example using completionPath, from lang-js

As the title said, this is a used examples of completionPath, It’s for autocompletion, and when we use ‘console.’, we want all the methods and properties about it to appear. This is where ‘completionPath’ comes into play.
I won’t cover it too much, it’s not a tutorial, it’s more like sample code, maybe I’ll describe it in more detail in the future if I have time.
If you don’t have a clue about autocompletion, you can check out the official examples or discussion:
example
discuss


如标题所说,这是一个使用 completionPath的例子,它作用于自动补全,当我们使用console.的时候,我们希望出现关于它的所有方法和属性,这时候completionPath就发挥了它的作用。
我不会过多的介绍,它不是一个教程,更像示例代码,也许未来我会更详细的去描述,如果我有时间的话。
关于自动补全,如果你没有头绪,你可以查看官方的例子或讨论:
例子
讨论

import { javascriptLanguage, completionPath } from '@codemirror/lang-javascript'
import { markdownLanguage } from '@codemirror/lang-markdown'

//Autocompletion methods
//自动补全方法 
let kwCompletion = name => ({ label: name, type: 'keyword' })
let fnCompletion = name => ({ label: name, type: 'function' })
let clCompletion = name => ({ label: name, type: 'class' })
let twCompletion = (name, prefix) => ({ label: prefix + name, type: 'keyword' })
//Autocomplete data
//自动补全数据 
const keywords =
	'break case catch class const continue debugger default delete do else export extends false finally for function if import in instanceof let new null return super switch this throw true try typeof var void while with yield await async enum implements interface package private protected public static'
		.split(' ')
		.map(kwCompletion)

const functions =
	'alert prompt confirm setTimeout setInterval clearTimeout clearInterval eval parseInt parseFloat isNaN isFinite encodeURI decodeURI encodeURIComponent decodeURIComponent window document navigator location history screen fetch async await'
		.split(' ')
		.map(fnCompletion)

const classes =
	'String Array Object Number Boolean RegExp Function Promise Map Set WeakMap WeakSet Symbol Error TypeError SyntaxError RangeError ReferenceError URIError EvalError Proxy Reflect Generator GeneratorFunction AsyncFunction ArrayBuffer DataView Int8Array Uint8Array Uint8ClampedArray Int16Array Uint16Array Int32Array Uint32Array Float32Array Float64Array BigInt64Array BigUint64Array BigInt'
		.split(' ')
		.map(clCompletion)
const tailwindWidthKeywords =
	'0 px 0.5 1 1.5 2 2.5 3 3.5 4 5 6 7 8 9 10 11 12 14 16 20 24 28 32 36 40 44 48 52 56 60 64 72 80 96 full min max auto 1/2 1/3 2/3 1/4 2/4 3/4 1/5 2/5 3/5 4/5 1/6 2/6 3/6 4/6 5/6 1/12 2/12 3/12 4/12 5/12 6/12 7/12 8/12 9/12 10/12 11/12 screen'
		.split(' ')
		.map(e => twCompletion(e, 'w-'))
// Define a completions object that contains common methods and objects
//定义一个包含常用方法和对象的 completions 对象
const completions = {
	// console object, containing its properties and methods
//console 对象,包含它的属性和方法
	console: {
		log: null,
		error: null,
		warn: null,
		// 其他的属性和方法,例如 clear,dir,assert 等
		// ...
	},
	// Math 对象,包含它的属性和方法
	Math: {
		PI: null,
		E: null,
		abs: null,
		sin: null,
		cos: null,
		// 其他的属性和方法,例如 max,min,random,sqrt 等
		// ...
	},
	// Date 对象,包含它的属性和方法
	Date: {
		now: null,
		parse: null,
		UTC: null,
		// 其他的属性和方法,例如 getFullYear,getMonth,getDate,getTime 等
		// ...
	},
	JSON: {
		parse: null,
		stringify: null,
	},
	// 其他的常用方法和对象,例如 JSON,Array,String,Number 等
	// ...
}
const variables = new Set(['console', 'Math', 'Date', 'JSON'])

const methods = new Set(['log', 'sin', 'abs', 'cos', 'now', 'parse', 'stringify'])
const propertys = new Set(['PI', 'E'])
//Autocompletion methods
// 自动补全方法
//Define a utility method to turn the completion information into a complete source
// 定义一个工具方法,将补全信息全部变成补全源的形式
function toCompletionSource(arr) {
	return arr.map(label => {
		let type
		if (variables.has(label)) type = 'variable'
		else if (methods.has(label)) type = 'function'
		else if (propertys.has(label)) type = 'property'
		return { label, type }
	})
}

function myCompletions(context) {
	let before = context.matchBefore(/[\w\.]+/)
	if (!context.explicit && !before) return null
	let { path, name } = completionPath(context) || {}
//It returns null inside the string,You can find instructions on the npm website
	// 在字符串内会返回null
	if (!path && !name) return
	let options = []
	let current = completions
	for (let p of path) {
		if (current[p]) current = current[p]
		else return null
	}

	if (!current) return
	else current = Object.keys(current)
	options = toCompletionSource(current)
	return {
		from: context.pos - name.length,
		to: context.pos,
		options: options,
		validFor: /^\w*$/,
	}
}
//This method is an autocompletion function created for some keywords. It doesn't work with '. 'in front of it, because you don't want to' console. 'with some keyword in it
//这个方法是为一些关键字创建的自动补全函数,它前面没有出现`.`时工作,因为你不会想`console.`的时候出现一些关键字
function myEasyCompletions(context) {
	let before = context.matchBefore(/\.+\w*/)
	// 出现.就不进行语法提示
	if (before) return
	before = context.matchBefore(/\w+/)
	if (!context.explicit && !before) return null
	return {
		from: before ? before.from : context.pos,
		options: keywords.concat(functions).concat(classes),
		validFor: /^\w*$/,
	}
}
//Autocomplete extensions
//自动补全扩展
const myJSCompletions_1 = javascriptLanguage.data.of({
	autocomplete: myEasyCompletions,
})
const myJSCompletions_2 = javascriptLanguage.data.of({
	autocomplete: myCompletions,
})
const myMarkdownCompletions = markdownLanguage.data.of({
	autocomplete: tailwindWidthKeywords,
})
//export
// 导出
export const languageExtension = [myJSCompletions_1, myJSCompletions_2, myMarkdownCompletions]

Here’s how it works


下面是使用效果
image