In Sublime Text, how can I replace a character with its Unicode? - unicode

In Sublime Text, how can I replace a character with its Unicode? For example, I want to replace 中 with 4E2D (or \u4E2D or something similar).

Sublime Text can be extended through Python plugins:
Sublime comes with functionality that generates a skeleton of Python code needed to write a simple plugin. Select Tools | Developer | New Plugin... in the menu.
Replace its content with the following code snippet:
import sublime
import sublime_plugin
class SwapuniCommand(sublime_plugin.TextCommand):
def run( self, edit):
for region in self.view.sel():
if not region.empty():
# Get the selected text
s = self.view.substr(region)
# Transform it
x = s.encode('raw_unicode_escape').decode()
if x == s:
x = s.encode('raw_unicode_escape').decode('unicode_escape')
# Replace the selection with transformed text
self.view.replace(edit, region, x)
Save to Packages/User/swapuni.py.
You can run it via entering view.run_command('swapuni') in the Sublime Text console (accessible via Ctrl+~), or by the following sublime-keymap (use your own keyboard shortcut in Preferences | Key Bindings):
[
{ "keys": ["ctrl+alt+r"], "command": "swapuni" }
]

Related

VSCode snippets: How to edit each line of text from clipboard before pasting?

Is there a way in visual studio code to edit each line of text from the clipboard before pasting?
I want to create a snippet that will run at the appropriate key combination, edit the text that is copied, and then paste it.
For example:
INPUT - I have a few lines of text. I copy them.
BANANA
APPLE
ORANGE
I paste the text using a combination of keys, such as ctrl + w, and I am expecting the output:
1 - BANANA - SOME TEXT,
2 - APPLE - SOME TEXT,
3 - ORANGE - SOME TEXT,
I know that I can set the cursor at the beginning of each line and paste the text, but I'm looking for a faster solution that can additionally be extended with more conditions. E.g.:
if the word "large" occurs in the text, replace it with "small",
number the lines of text,etc.
Using the extension Find and Transform, which I wrote, make this keybinding in your keybindings.json (or it could be a setting):
{
"key": "alt+f", // whatever keybinding you want
"command": "findInCurrentFile",
"description": "modify the clipboard",
"args": {
"run": [
"$${",
"const selectedText = document.getText(vscode.window.activeTextEditor.selection);",
"const lines = selectedText.split(/\\r?\\n/);", // to handle different OS's
"let newStr = '';",
"lines.forEach((line, index) => {",
"if (line === 'APPLE') line = 'small';",
"newStr += `${index+1} - ${line} - some text,\\n`;", // double-escape \\n
"});",
"newStr = newStr.slice(0, -1);", // remove last \n from newStr
"vscode.env.clipboard.writeText(newStr);",
// "return newStr",
"}$$"
]
}
}
In the body of the run value you can do any string manipulation you want. It ends by writing the new string to the clipboard as you requested.
If you just wanted to immediately replace what you have selected with the result change the run line to
// "run": [
"replace": [
and instead of writing to the clipboard just return the result:
// "vscode.env.clipboard.writeText(newStr);",
"return newStr",
"}$$"

VS Code Markdown Bold Shortcut Not Working

Usually, cmd + b or ctrl + b (in Windows) will make the selected text bold in a Markdown file but that's not working. How can I fix it?
By default, cmd + b is the keyboard shortcut for toggling sidebar visibility. To change it, add the following block of code in the keybindings.json file:
{
"key": "cmd+b",
"scope": "markdown",
"command":"editor.action.insertSnippet",
"when":"editorTextFocus && editorLangId == 'markdown'",
"args":{
"snippet":"**$TM_SELECTED_TEXT**$0"
}
}

How to Enable MathJax Upgreek in jupyter/ipython notebook?

I have reviewed various related questions including
How do I get MathJax to enable the mhchem extension in ipython notebook
IPython (Jupyter) MathJaX preamble
but I cannot get it to work...
My test case is simply
from IPython.display import display, HTML, Math, Latex
display(Math(r'\uppi'))
expecting upright $\pi$ but currently getting just '\uppi' back raw.
I have tried the following using cell magic
%%javascript
<script type="text/Javascript">
MathJax.Hub.Config({
loader: {load: ['[tex]/upgreek']},
tex: {packages: {'[+]': ['upgreek']}}
});
</script>
which generates Javascript Error: Unexpected token '<'
%%javascript
MathJax.Hub.Config({
loader: {load: ['[tex]/upgreek']},
tex: {extensions: ['require.js'], packages: {'[+]': ['upgreek']}}
});
which throws no error but doesn't seem to have any effect
%%javascript
window.MathJax = {
loader: {load: ['[tex]/upgreek']},
tex: {packages: {'[+]': ['upgreek']}}
};
which also does not seem to have the desired effect
Question: I don't want to modify configuration/javascript files outside the notebook. How can I enable MathJax upgreek dynamically in a jupyter notebook?
(Currently on jupyterlab 3.2.2, python 3.8.10 under Windows 10)
This does not address the OP's fundamental issue, which relates to the control of the installation of MathJax extensions in jupyter, but it does address the objective: to alter the rendered appearance of greek symbols (but can be applied to other font-related needs as well)
Updated
The following will create TeX macros for all upper and lower case greek characters, as also available in Upgreek if it could be installed.
from IPython.display import display, Math
# Using codes from https://unicode-table.com/en/sets/greek-symbols/, create dictionaries of unicodes keyed by character names
grLcUpChars = [rf'\unicode{{{code}}}' for code in range(0x3B1, 0x3CA) if code != 0x3C2] # omit 'final sigma'
grUcUpChars = [rf'\unicode{{{code}}}' for code in range(0x391, 0x3AA) if code != 0x3A2] # omit omitted code for 'final sigma' in uppercase
grCharNames = ['alpha', 'beta', 'gamma', 'delta', 'epsilon', 'zeta', 'eta', 'theta', 'iota', 'kappa', 'lambda',
'mu', 'nu', 'xi', 'omicron', 'pi', 'rho', 'sigma', 'tau', 'upsilon', 'phi', 'chi', 'psi', 'omega']
zipIt = zip(grCharNames, grLcUpChars)
grLcUpDict = dict(zipIt)
zipIt = zip(grCharNames, grUcUpChars)
grUcUpDict = dict(zipIt)
# Generate the MathJax code to create 'macro' definitions for upright greek characters
# See e.g. https://docs.mathjax.org/en/latest/input/tex/macros.html
# Paste output text from $ to $ inclusive into a markdown cell and execute it
print('$')
for grCharName in grCharNames:
print(fr' \def\Up{grCharName}{{{{{grLcUpDict[grCharName]}}}}}')
for grCharName in grCharNames:
print(fr' \def\Up{grCharName.title()}{{{{{grUcUpDict[grCharName]}}}}}')
print('$')
which produces the TeX macros for a Markdown cell:
$
\def\Upalpha{{\unicode{945}}}
\def\Upbeta{{\unicode{946}}}
\def\Upgamma{{\unicode{947}}}
\def\Updelta{{\unicode{948}}}
\def\Upepsilon{{\unicode{949}}}
\def\Upzeta{{\unicode{950}}}
\def\Upeta{{\unicode{951}}}
\def\Uptheta{{\unicode{952}}}
\def\Upiota{{\unicode{953}}}
\def\Upkappa{{\unicode{954}}}
\def\Uplambda{{\unicode{955}}}
\def\Upmu{{\unicode{956}}}
\def\Upnu{{\unicode{957}}}
\def\Upxi{{\unicode{958}}}
\def\Upomicron{{\unicode{959}}}
\def\Uppi{{\unicode{960}}}
\def\Uprho{{\unicode{961}}}
\def\Upsigma{{\unicode{963}}}
\def\Uptau{{\unicode{964}}}
\def\Upupsilon{{\unicode{965}}}
\def\Upphi{{\unicode{966}}}
\def\Upchi{{\unicode{967}}}
\def\Uppsi{{\unicode{968}}}
\def\Upomega{{\unicode{969}}}
\def\UpAlpha{{\unicode{913}}}
\def\UpBeta{{\unicode{914}}}
\def\UpGamma{{\unicode{915}}}
\def\UpDelta{{\unicode{916}}}
\def\UpEpsilon{{\unicode{917}}}
\def\UpZeta{{\unicode{918}}}
\def\UpEta{{\unicode{919}}}
\def\UpTheta{{\unicode{920}}}
\def\UpIota{{\unicode{921}}}
\def\UpKappa{{\unicode{922}}}
\def\UpLambda{{\unicode{923}}}
\def\UpMu{{\unicode{924}}}
\def\UpNu{{\unicode{925}}}
\def\UpXi{{\unicode{926}}}
\def\UpOmicron{{\unicode{927}}}
\def\UpPi{{\unicode{928}}}
\def\UpRho{{\unicode{929}}}
\def\UpSigma{{\unicode{931}}}
\def\UpTau{{\unicode{932}}}
\def\UpUpsilon{{\unicode{933}}}
\def\UpPhi{{\unicode{934}}}
\def\UpChi{{\unicode{935}}}
\def\UpPsi{{\unicode{936}}}
\def\UpOmega{{\unicode{937}}}
$
For clarity & test, in another cell, this will list the defined macro names and display the upper and lower case alphabets
grLcAlphabetMathJax = [fr'\Up{grCharName}' for grCharName in grCharNames]
grUcAlphabetMathJax = [fr'\Up{grCharName.title()}' for grCharName in grCharNames]
display(grLcAlphabetMathJax)
display(grUcAlphabetMathJax)
display(Math(''.join(grLcAlphabetMathJax)))
display(Math(''.join(grUcAlphabetMathJax)))
Thereby effectively reproducing Upgreek; skipping the lists its output is:
αβγδεζηθικλμνξοπρστυφχψω
ΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡΣΤΥΦΧΨΩ
Superseded Original
Workaround: referring to this excellent MathJax/TeX documentation we find the \unicode instruction for MathJax, and via this site the codes for an upright Pi symbol (as example).
This then allows the following in a notebook cell, after from IPython.display import display, HTML, Math, Latex
display(Math(r'\unicode[Segoe UI]{x03C0}'))
which generates π
whereas
display(Math(r'\unicode[familySTIXMathJax_Normal-italic]{x03C0}'))
generates an italicised 𝜋 (that attempting to switch to familySTIXMathJax_Normal does not seem to affect!?)
and ordinary display(Math(r'\pi')) generates 𝜋

How can vscode print (or paste) all open file paths to a new file in the editor?

In vscode Ctrl+Tab displays open files, but how can vscode print (or paste) the same 'all open file paths' to a new file in the editor?
If you have this setting set to a high enough number to show all your open files:
Editor > Open Editors: Visible
then you can select all the files from the Open Editors viewlet (with Ctrl+A for instance) in the Explorer, right-click and choose Copy Path or Copy Relative Path and then paste it yourself into a new file. Demo:
For how to automatically send selected (modify the variable for clipboard text) to a new file see my answer at https://stackoverflow.com/a/57612004/836330. I suppose the whole thing might be made into a macro.
Here is the macro. Using a macro extension like multi-command put this into your settings.json:
"multiCommand.commands": [
{
"command": "multiCommand.getOpenFilePaths",
"sequence": [
"workbench.files.action.focusOpenEditorsView",
"list.selectAll",
"copyFilePath", // full paths
// "copyRelativeFilePath", // relative paths
"workbench.action.files.newUntitledFile",
"editor.action.clipboardPasteAction",
// prompt for save immediately?
// "workbench.action.files.saveAs",
]
}
]
and some keybinding to trigger that macro:
{
"key": "alt+o", // whatever keybinding you wish
"command": "extension.multiCommand.execute",
"args": { "command": "multiCommand.getOpenFilePaths" },
},
The Open Editors viewlet can be collapsed if you wish when you trigger the macro and it still works. Demo:
[Adding another answer because the first was long and very different.]
Here is a simpler way to print a list of the currently open files to a newly created file. It does not require that the Open Editors view be visible. It uses newer extension api to access the tabs currently open.
It uses an extension (I wrote), Find and Transform. In this extension, you can use the vscode extension api. Make this keybinding (in your keybindings.json) (it could also be made into a command accessible from the Command Palette):
{
"key": "alt+q", // whatever keybinding you want
"command": "findInCurrentFile",
"args": {
"replace": [
"$${",
"let str = '';",
"const groups = vscode.window.tabGroups.all;", // if multiple editor groups
"groups.map((group, index) => {",
"str += 'Group ' + (index+1) + '\\n';",
"group.tabs.map(tab => {",
"if (tab.input instanceof vscode.TabInputText) str += '\\t' + tab.input.uri.fsPath + '\\n';",
// the above prints the full path, use below if you only want the tab file label only
// "str += tab.label + '\\n';",
"});",
"str += '\\n';",
"});",
"vscode.env.clipboard.writeText( str );",
"return '';",
"}$$"
],
// open a new file and paste to it
"postCommands": ["workbench.action.files.newUntitledFile", "editor.action.clipboardPasteAction"]
},
}
To open a save file dialog use this "postCommands" entry.
"postCommands": [
"workbench.action.files.newUntitledFile",
"editor.action.clipboardPasteAction",
"workbench.action.files.save"
]

Eclipse: selection autocopy to clipboard

I love an Emacs feature to copy selection to clipboard automatically. Is it possible to do the same on Eclipse?
Environment: Windows XP, Helios
To copy a String from Eclipse to the clipboard, you can use
void copyToClipboard (String toClipboard, Display display){
String toClipboard = "my String";
Clipboard clipboard = new Clipboard(display);
TextTransfer [] textTransfer = {TextTransfer.getInstance()};
clipboard.setContents(new Object [] {toClipboard}, textTransfer);
clipboard.dispose();
}
Then you can call this method from a MouseAdapter or KeyAdapter, depending on where you want to get your String from. In your case it could be MouseAdapter, which listens to doubleclicks, gets the current cursor position of the text, marks the word and then adds the String to the clipboard.
edit to answer a question: You can set up your own MouseAdapater and attach it to buttons, text fields or whateer you like. Here's an example for a button:
Button btnGo1 = new Button(parent, SWT.NONE);
btnGo1.setText("Go");
btnGo1.addMouseListener(new MouseAdapter() {
#Override
public void mouseDoubleClick(MouseEvent e) {
//do what you want to do in here
}
});
If you want to implement mouseUp and mouseDown events, too, you can just add MouseListenerinstead of the Adapter. The only advantage of the Adapter is, that you don't have to override the other methods of the interface.
Since the original question was to automatically get the selection of the text of an editor: the way to get the selection from an editor is explained here.
You can try this plugin. Along with auto copy points mentioned in Eclipse show number of lines and/or file size also addressed.