Giter VIP home page Giter VIP logo

linkify-it-rb's Introduction

linkify-it-rb

Gem Version Build Status

This gem is a port of the linkify-it javascript package by Vitaly Puzrin, that is used for the markdown-it package.

Currently synced with linkify-it 4.0.1


Links recognition library with full unicode support. Focused on high quality link pattern detection in plain text. For use with both Ruby and RubyMotion.

Javascript Demo

Features:

  • Full unicode support, with astral characters
  • International domain support
  • Allows rules extension & custom normalizers

Install

Ruby

Add it to your project's Gemfile

gem 'linkify-it-rb'

and run bundle install

RubyMotion

Add it to your project's Gemfile

gem 'linkify-it-rb'

Edit your Rakefile and add

require 'linkify-it-rb'

and run bundle install

Usage examples

Example 1
linkify = Linkify.new

# Reload full tlds list & add unofficial `.onion` domain.
linkify.tlds('onion', true)      # Add unofficial `.onion` domain
linkify.add('git:', 'http:')     # Add `git:` protocol as "alias"
linkify.add('ftp:', null)        # Disable `ftp:` protocol
linkify.set({fuzzyIP: true})     # Enable IPs in fuzzy links (without schema)

linkify.test('Site github.com!'))
=> true

linkify.match('Site github.com!'))
=> [#<Linkify::Match @schema="", @index=5, @lastIndex=15, @raw="github.com", @text="github.com", @url="github.com">]
Example 2. Add twitter mentions handler
linkify.add('@', {
  validate: lambda do |text, pos, obj|
    tail = text.slice(pos..-1)
    if (!obj.re[:twitter])
      obj.re[:twitter] =  Regexp.new('^([a-zA-Z0-9_]){1,15}(?!_)(?=$|' + LinkifyRe::SRC_Z_P_CC + ')')
    end
    if (obj.re[:twitter] =~ tail)
      return 0 if (pos >= 2 && text[pos - 2] == '@')
      return tail.match(obj.re[:twitter])[0].length
    end
    return 0
  end,
  normalize: lambda do |m, obj|
    m.url = 'https://twitter.com/' + m.url.sub(/^@/, '')
  end
})

API

LinkifyIt.new(schemas, options)

Creates new linkifier instance with optional additional schemas.

By default understands:

  • http(s)://... , ftp://..., mailto:... & //... links
  • "fuzzy" links and emails (google.com, [email protected]).

schemas is a Hash, where each key/value describes protocol/rule:

  • key - link prefix (usually, protocol name with : at the end, skype: for example). linkify-it-rb makes sure that prefix is not preceded with alphanumeric char.
  • value - rule to check tail after link prefix
    • String - just alias to existing rule
    • Hash
      • validate - either a RegExp (start with ^`, and don't include the link prefix itself), or a validator block which, given arguments, text, pos, and self, returns the length of a match in text starting at index pos. pos is the index right after the link prefix. self can be used to access the linkify object to cache data.
      • normalize - optional block to normalize text & url of matched result (for example, for twitter mentions).

options:

  • fuzzyLink - recognize URL-s without http(s):// head. Default true.
  • fuzzyIP - allow IPs in fuzzy links above. Can conflict with some texts like version numbers. Default false.
  • fuzzyEmail - recognize emails without mailto: prefix. Default true.
  • --- - set true to terminate link with --- (if it's considered as long dash).

.test(text)

Searches linkifiable pattern and returns true on success or false on fail.

.pretest(text)

Quick check if link MAYBE can exist. Can be used to optimize more expensive .test calls. Return false if link can not be found, true - if .test call needed to know exactly.

.testSchemaAt(text, name, offset)

Similar to .test but checks only specific protocol tail exactly at given position. Returns length of found pattern (0 on fail).

.match(text)

Returns Array of found link matches or nil if nothing found.

Each match has:

  • schema - link schema, can be empty for fuzzy links, or // for protocol-neutral links.
  • index - offset of matched text
  • lastIndex - index of next char after mathch end
  • raw - matched text
  • text - normalized text
  • url - link, generated from matched text

.matchAtStart(text)

Checks if a match exists at the start of the string. Returns Match (see docs for match(text)) or nil if no URL is at the start. Doesn't work with fuzzy links.

.tlds(list[, keepOld])

Load (or merge) new tlds list. These are needed for fuzzy links (without schema) to avoid false positives. By default this algorithm uses:

  • 2-letter root zones are ok.
  • biz|com|edu|gov|net|org|pro|web|xxx|aero|asia|coop|info|museum|name|shop|ั€ั„ are ok.
  • encoded (xn--...) root zones are ok.

If that's not enough, you can reload defaults with more detailed zones list.

.add(key, value)

Add a new schema to the schemas object. As described in the constructor definition, key is a link prefix (skype:, for example), and value is a String to alias to another schema, or an Object with validate and optionally normalize definitions. To disable an existing rule, use .add(key, null).

.set(options)

Override default options. Missed properties will not be changed.

License

MIT

linkify-it-rb's People

Contributors

digitalmoksha avatar mrysav avatar

Stargazers

 avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.