Add "add link" shortcut

This commit is contained in:
Matt Baer 2017-08-04 18:06:05 -04:00
parent 81aa1bed98
commit 5ed52f4eb2
4 changed files with 23 additions and 1 deletions

View File

@ -95,6 +95,11 @@ class AppDelegate: NSObject, NSApplicationDelegate {
wc?.emphasize()
}
@IBAction func formatAddLink(_ sender: Any) {
let wc = NSApplication.shared().mainWindow?.windowController as? WindowController
wc?.addLink()
}
@IBAction func setFontSerif(_ sender: NSMenuItem) {
deselectAllFonts()
sender.state = NSOnState

View File

@ -333,6 +333,12 @@ DQ
<action selector="formatEmphasis:" target="Voe-Tx-rLC" id="uTS-Jh-2A2"/>
</connections>
</menuItem>
<menuItem isSeparatorItem="YES" id="SmR-t9-22S"/>
<menuItem title="Add Link" keyEquivalent="k" id="GUY-qo-vEn">
<connections>
<action selector="formatAddLink:" target="Voe-Tx-rLC" id="0Le-n0-qwE"/>
</connections>
</menuItem>
</items>
</menu>
</menuItem>

View File

@ -94,18 +94,26 @@ class ViewController: NSViewController, NSTextViewDelegate, NSUserNotificationCe
formatText(with: "_\(getSelectedText())_", offset: 1)
}
func addLink() {
let text = getSelectedText()
formatText(with: "[\(text)](http://)", offset: text == "" ? 1 : (text.characters.count + 10), alwaysOffset: true)
}
fileprivate func getSelectedText() -> String {
let selectedRange = writerText.selectedRange()
return (self.writerText.textStorage?.string as! NSString).substring(with: selectedRange)
}
fileprivate func formatText(with: String, offset: Int) {
formatText(with: with, offset: offset, alwaysOffset: false)
}
fileprivate func formatText(with: String, offset: Int, alwaysOffset: Bool) {
let selectedRange = writerText.selectedRange()
let selString = getSelectedText()
if self.writerText.shouldChangeText(in: selectedRange, replacementString: with) {
self.writerText.replaceCharacters(in: NSRange(location: selectedRange.location, length: selectedRange.length), with: with)
self.writerText.didChangeText()
if selString == "" {
if selString == "" || alwaysOffset {
writerText.setSelectedRange(NSRange(location: selectedRange.location + offset, length: 0))
}
}

View File

@ -34,4 +34,7 @@ class WindowController: NSWindowController {
func emphasize() {
vc?.emphasize()
}
func addLink() {
vc?.addLink()
}
}