Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save shabegom/a47745a7a8ae9a9729ca007e88690e59 to your computer and use it in GitHub Desktop.
Save shabegom/a47745a7a8ae9a9729ca007e88690e59 to your computer and use it in GitHub Desktop.
Move the active line of the active file to a chosen file.
<%*
//v1.1: Choose where to move line to in file
//'first' will add to top of file. 'last' will add to bottom of file
let firstOrLastLine = 'last';
//Choose a specific line to move to underneath; overrules firstOrLastLine if true
const bChooseLine = false;
//After moving the line, open the file it was moved to
const bOpenFile = false;
const moveToFile = await tp.system.suggester((item) => item.path, this.app.vault.getMarkdownFiles(), false);
if(moveToFile) {
let cmEditorAct = this.app.workspace.activeLeaf.view.sourceMode.cmEditor;
const curLine = cmEditorAct.getCursor().line;
cmEditorAct.setSelection({ line: curLine, ch: 0 }, { line: curLine, ch: 9999 });
const selectedText = tp.file.selection();
tR = selectedText;
const curContent = await this.app.vault.read(moveToFile);
let newContents;
let selectLine;
if(bChooseLine) {
const arrayEachLine = curContent.split('\n');
let arrayStrings = ['--End of File--', '--Beginning of File--'];
let arrayValues = ['last_', 'first_'];
arrayEachLine.forEach(eachItem => {
if(eachItem != '') {
arrayStrings.push(eachItem.slice(0,250));
arrayValues.push(eachItem);
}
});
selectLine = await tp.system.suggester(arrayStrings, arrayValues, false);
if(selectLine == 'last_' || selectLine == 'first_') {
if(selectLine == 'first_'){
firstOrLastLine = 'first';
newContents = selectedText + '\n' + curContent
} else {
firstOrLastLine = 'last';
newContents = curContent + '\n' + selectedText
}
} else {
newContents = curContent.replace('\n' + selectLine + '\n', '\n' + selectLine + '\n' + selectedText + '\n');
}
} else {
if(firstOrLastLine == 'first'){
newContents = selectedText + '\n' + curContent
}
else {
newContents = curContent + '\n' + selectedText
}
}
if(bChooseLine == false || selectLine) {
await this.app.vault.modify(moveToFile, newContents);
if(bOpenFile) {
await this.app.workspace.openLinkText(moveToFile.basename, moveToFile.path, true);
if(bChooseLine == false || selectLine == 'last_' || selectLine == 'first_') {
cmEditorAct = this.app.workspace.activeLeaf.view.sourceMode.cmEditor;
if(firstOrLastLine == 'first'){
cmEditorAct.setSelection({ line: 0, ch: 0 }, { line: 0, ch: 9999 });
}
else {
cmEditorAct.setSelection({ line: cmEditorAct.lastLine(), ch: 0 }, { line: cmEditorAct.lastLine(), ch: 9999 });
}
}
}
tR = '';
}
}
%>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment